Get height of multi line text with fixed width to make dialog resize properly

前端 未结 3 1580
别那么骄傲
别那么骄傲 2021-01-02 08:31

I want to create a dialog that contains some kind of text element (JLabel/JTextArea etc) that is multi lined and wrap the words. I want the dialog to be of a fixed width but

3条回答
  •  一向
    一向 (楼主)
    2021-01-02 09:15

    I found a solution to my problem. By replacing the JLabel with a JTextArea:

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

    And calling pack() followed by an invocation to the layout manager to layout the components again followed by another pack:

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

    This will cause the layout manager to adapt to the width.

    The complete code:

    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);
          }
        });
      }
    }
    

    (you can add some customization (border, color etc) so it looks just like the JLabel but I have omitted that)

提交回复
热议问题