Dynamically change the width of JDialog

孤人 提交于 2019-12-06 10:59:47
mKorbel
  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).

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.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!