【发布时间】:2009-07-17 11:59:24
【问题描述】:
我总是对 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 的引用,当一个组件是一个单独的类时,它会变得混乱。让这个示例运行的首选方法是什么?
【问题讨论】: