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!
getPreferredSize
forJLabel
- basically you have to gettextLength
fromJLabel
in pixels, there are 3 correct ways, but I love:SwingUtilities.computeStringWidth(FontMetrics fm, String str)
Now you are able to
setPreferredSize
forJLabel
correctly (please by defalut is there needed to add +5 - +10 to theInteger
that returnsSwingUtilities.computeStringWidth
)- Call
pack();
on the top level container (theJDialog
).
Try invoking I just realized that this will not work. validate()
on the JDialog
.
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.
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);
}
});
}
}
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.
Trying using the validate()
method, this will cause the JDialog
to lay out its subcomponents again
EDIT
This apparently will not work
来源:https://stackoverflow.com/questions/6845382/dynamically-change-the-width-of-jdialog