我总是在 Java 布局方面遇到麻烦,但现在困扰我的主要问题是,当内容发生变化时,尤其是更改其大小时,它不会再次正确布局。举个例子:
package layouttest;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class LayoutTestStart extends JFrame implements ActionListener
{
static JButton button= new JButton("Expand");
static JTextArea f = new JTextArea("A medium sized text");
static LayoutTestStart lst;
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI()
{
lst = new LayoutTestStart();
lst.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel all = new JPanel();
button.addActionListener(lst);
all.add(button);
all.add(f);
lst.getContentPane().add(all);
lst.setVisible(true);
lst.pack();
}
@Override
public void actionPerformed(ActionEvent e)
{
f.setText(f.getText()+"\n"+f.getText());
// this doesn't work
f.invalidate();
// this does but it's cheating
// lst.pack();
}
}
我让它工作的唯一方法是调用 lst.pack(),但这是作弊,因为那时每个组件都应该有一个对它的 JFrame 的引用,当一个组件是一个单独的类时它会变得困惑。让这个示例工作的首选方法是什么?
最佳答案
revalidate
而不是 invalidate
。 invalidate
只是将容器标记为需要布局。 revalidate
执行此操作,然后安排 validate
。
顺便说一句:我建议:避免从 JFrame
和其他组件扩展;避免接口(interface)的多重继承并避免(可变的)静态。
关于java - 让 Java Swing 程序重新布局自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1142827/