gpt4 book ai didi

java - 动态添加按钮框架

转载 作者:行者123 更新时间:2023-12-01 18:33:51 25 4
gpt4 key购买 nike

我有一个 JFrame 类

public class SettingsFrame extends JFrame {
public FirstSettingsFrame() throws HeadlessException {
setTitle("Settings");
setSize(600, 400);
...
JButton searchModels = new JButton("Start");
searchManyModels.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent actionEvent) {

JFrame frame = new JFrame();
frame.setSize(new Dimension(800, 600));
frame.setLayout(null);
frame.setVisible(true);

for (int i = 0; i < 10; i++) {
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
JButton button = new JButton("Test");
button.setBounds(i * 10, i * 10, 20, 20);
frame.add(button);
System.out.println("i = " + i);
}
}
});

add(searchModels);
...
}

当循环正在处理时,没有添加任何内容。仅当循环完成时才添加所有按钮。我希望在循环时添加它们。我该如何处理这个问题?

编辑:

这段代码

 @Override
public void actionPerformed(ActionEvent actionEvent) {


JFrame frame = new JFrame();
JPanel panel = new JPanel();

frame.setSize(new Dimension(800, 600));

frame.add(panel);
frame.pack();
frame.setVisible(true);

for (int i = 0; i < 10; i++) {
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}

JButton button = new JButton("Test");
button.setBounds(i * 10, i * 10, 20, 20);
panel.add(button);

panel.revalidate();
panel.repaint();
frame.pack();
System.out.println("i = " + i);
}
}
});

仅更改帧大小,循环时也不添加任何内容

编辑2:

删除 Thread.sleep 并编写循环 for (long i = 0; i < 100000000000l; i++) { 根本不会影响。

最佳答案

不要使用空布局!!!

Swing 被设计为与布局管理器一起使用。那么从可见 GUI 添加/删除组件的基本代码是:

panel.add(...);
panel.revalidate(); // to invoke layout manager
panel.repaint(); // to paint components.

阅读 Swing 教程中关于 How to Use Layout Managers 的部分了解更多信息。

All buttons are added only when loop is finished. And i want them to be added while looping. How can i manage this?

Thread.sleep() 正在阻塞事件调度线程,因此 GUI 无法重新绘制自身,直到循环执行完毕。查看我上面提供的链接中的目录,并阅读并发教程中的部分以获取更多信息。您应该使用 Swing Timer(这也是本教程中的一个主题),而不是循环。

关于java - 动态添加按钮框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22917749/

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