Obter altura de múltiplas linhas de texto com largura fixa para fazer redimensionamento de diálogo corretamente

StackOverflow https://stackoverflow.com/questions/1048224

  •  20-08-2019
  •  | 
  •  

Pergunta

Eu quero criar um diálogo que contém algum tipo de elemento de texto (JLabel / JTextArea etc) que é multi alinhados e enrole as palavras. Eu quero o diálogo para ser de uma largura fixa, mas se adaptar a altura dependendo de quão grande o texto é. Eu tenho esse código:

import static javax.swing.GroupLayout.DEFAULT_SIZE;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class TextSizeProblem extends JFrame {
  public TextSizeProblem() {

    String dummyString = "";
    for (int i = 0; i < 100; i++) {
      dummyString += " word" + i;  //Create a long text
    }
    JLabel text = new JLabel();
    text.setText("<html>" + dummyString + "</html>");

    JButton packMeButton = new JButton("pack");
    packMeButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        pack();
      }
    });

    GroupLayout layout = new GroupLayout(this.getContentPane());
    getContentPane().setLayout(layout);
    layout.setVerticalGroup(layout.createParallelGroup()
        .addComponent(packMeButton)
        .addComponent(text)
    );
    layout.setHorizontalGroup(layout.createSequentialGroup()
        .addComponent(packMeButton)
        .addComponent(text, DEFAULT_SIZE, 400, 400) //Lock the width to 400
    );

    pack();
  }

  public static void main(String args[]) {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        JFrame frame = new TextSizeProblem();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
      }
    });
  }
}

Ao executar o programa se parece com isso: text alt
(fonte: lesc.se )

Mas eu gostaria de diálogo para olhar como este (como quando você pressiona o botão pack): text alt
(fonte: lesc.se )

Eu estou supondo que o problema é que o gerenciador de layout não tinha sido capaz de determinar a altura adequada do texto antes de exibi-lo na tela. Eu tentei vários validate (), invalidate (), validateTree () etc, mas não ter sucesso.

Foi útil?

Solução 3

Eu encontrei uma solução para o meu problema. Ao substituir o JLabel com um JTextArea:

JTextArea text = new JTextArea();
text.setText(dummyString);
text.setLineWrap(true);
text.setWrapStyleWord(true);

E pacote de telefone () seguido por uma invocação ao gerenciador de layout para o layout os componentes novamente seguido por um outro pacote:

pack();
layout.invalidateLayout(this.getContentPane());
pack();

Isto fará com que o gerenciador de layout para se adaptar à largura.

O código completo:

import static javax.swing.GroupLayout.DEFAULT_SIZE;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class TextSizeProblem3 extends JFrame {
  public TextSizeProblem3() {

    String dummyString = "";
    for (int i = 0; i < 100; i++) {
      dummyString += " word" + i;  //Create a long text
    }
    JTextArea text = new JTextArea();
    text.setText(dummyString);
    text.setLineWrap(true);
    text.setWrapStyleWord(true);

    JButton packMeButton = new JButton("pack");
    packMeButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        pack();
      }
    });

    GroupLayout layout = new GroupLayout(this.getContentPane());
    getContentPane().setLayout(layout);
    layout.setVerticalGroup(layout.createParallelGroup()
        .addComponent(packMeButton)
        .addComponent(text)
    );
    layout.setHorizontalGroup(layout.createSequentialGroup()
        .addComponent(packMeButton)
        .addComponent(text, DEFAULT_SIZE, 400, 400) //Lock the width to 400
    );

    pack();
    layout.invalidateLayout(this.getContentPane());
    pack();
  }

  public static void main(String args[]) {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        JFrame frame = new TextSizeProblem3();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
      }
    });
  }
}

(você pode adicionar um pouco de personalização (borda, cor etc) para que ele se parece com o JLabel mas omiti que)

Outras dicas

Aqui é uma adaptação do seu código, fazer o que quiser. Mas ele precisa de um pequeno truque para calcular o tamanho do rótulo e defina seu preferido Size.

eu encontrei a solução aqui

import static javax.swing.GroupLayout.DEFAULT_SIZE;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.text.View;

public class TextSizeProblem extends JFrame {
    public TextSizeProblem() {

        String dummyString = "";
        for (int i = 0; i < 100; i++) {
            dummyString += " word" + i; // Create a long text
        }
        JLabel text = new JLabel();
        text.setText("<html>" + dummyString + "</html>");

        Dimension prefSize = getPreferredSize(text.getText(), true, 400);

        JButton packMeButton = new JButton("pack");
        packMeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                pack();
            }
        });



        GroupLayout layout = new GroupLayout(this.getContentPane());
        getContentPane().setLayout(layout);
        layout.setVerticalGroup(layout.createParallelGroup().addComponent(packMeButton)
                .addComponent(text,DEFAULT_SIZE, prefSize.height, prefSize.height));
        layout.setHorizontalGroup(layout.createSequentialGroup().addComponent(packMeButton)
                .addComponent(text, DEFAULT_SIZE, prefSize.width, prefSize.width) // Lock the width to 400
                );

        pack();
    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new TextSizeProblem();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }

    private static final JLabel resizer = new JLabel();

    /**
     * Returns the preferred size to set a component at in order to render an html string. You can
     * specify the size of one dimension.
     */
    public static java.awt.Dimension getPreferredSize(String html, boolean width, int prefSize) {

        resizer.setText(html);

        View view = (View) resizer.getClientProperty(javax.swing.plaf.basic.BasicHTML.propertyKey);

        view.setSize(width ? prefSize : 0, width ? 0 : prefSize);

        float w = view.getPreferredSpan(View.X_AXIS);
        float h = view.getPreferredSpan(View.Y_AXIS);

        return new java.awt.Dimension((int) Math.ceil(w), (int) Math.ceil(h));
    }
}

Eu acho que isso é o que você quer:

JLabel label = new JLabel("<html><div style=\"width:200px;\">Lots of text here...</div></html>");
// add the label to some Container.

Isto irá restringir o JLabel a ser 200 pixels de largura e ajustar automaticamente a altura para ajustar o texto.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top