Dynamically change the width of JDialog

2019-05-26 21:55发布

问题:

I have created a JDialog which contains a JLabel. Because the length of text, which changes based on users' input, can contain a large number of characters, there is the need to dynamically change the length of the JDialog based on the size of length of the JDialog. I have tried the pack() method but it's not the case for it. Can anyone give me some tips? Thanks in advance!

回答1:

  1. getPreferredSize for JLabel - basically you have to get textLength from JLabel in pixels, there are 3 correct ways, but I love:

    SwingUtilities.computeStringWidth(FontMetrics fm, String str)
    
  2. Now you are able to setPreferredSize for JLabel correctly (please by defalut is there needed to add +5 - +10 to the Integer that returns SwingUtilities.computeStringWidth)

  3. Call pack(); on the top level container (the JDialog).


回答2:

Try invoking validate() on the JDialog. I just realized that this will not work.


Here's a nice thread that discusses this issue. I would recommend listening to the answer and suggestions provided by @Andrew Thompson, who's actually a prominent user here.



回答3:

Another alternative is to put the text into a JTextArea and put that in a JScrollPane.

E.G.

Code

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class ExpandingText {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                final String s = 
                    "The quick brown fox jumped over the lazy dog.  ";

                final JTextArea textArea = new JTextArea(s,5,30);
                textArea.setWrapStyleWord(true);
                textArea.setLineWrap(true);
                textArea.setEditable(false);
                textArea.setFocusable(false);

                JButton button = new JButton("Add Text");
                button.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent ae) {
                            textArea.append(s);
                        }
                    });

                JPanel panel = new JPanel(new BorderLayout(3,3));
                panel.add(button, BorderLayout.NORTH);
                panel.add(new JScrollPane(textArea), BorderLayout.CENTER);

                JOptionPane.showMessageDialog(null, panel);
            }
        });
    }
}


回答4:

Why will pack() not work for you?

You could use setSize and base the width off the width of the JLabel. Call this method whenever the user changes the input.



回答5:

Trying using the validate() method, this will cause the JDialog to lay out its subcomponents again

EDIT

This apparently will not work