gpt4 book ai didi

java - 让 Java Swing 程序重新布局自身

转载 作者:行者123 更新时间:2023-11-30 09:58:11 26 4
gpt4 key购买 nike

我总是在 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 而不是 invalidateinvalidate 只是将容器标记为需要布局。 revalidate 执行此操作,然后安排 validate

顺便说一句:我建议:避免从 JFrame 和其他组件扩展;避免接口(interface)的多重继承并避免(可变的)静态。

关于java - 让 Java Swing 程序重新布局自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1142827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com