gpt4 book ai didi

java - 如何重新加载 JFrame - Java

转载 作者:行者123 更新时间:2023-12-01 12:35:41 24 4
gpt4 key购买 nike

我正在用java编程,我想刷新我的Jframe并通过循环更改颜色,但我无法重新加载框架,但我只能创建一个新框架。

package frames;
import java.awt.Color;

import javax.swing.*;

public class Frame1 {
public static void main(String[] args)
{
int num = 0;



while (num<255)
{
num +=1;
JFrame frame = new JFrame();
frame.setSize(400,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(new Color(num,num,num));
frame.setTitle("");

}
}
}

最佳答案

  1. 您只需使用一帧(您将创建 255 个)
  2. 不要使用 while 循环来尝试更改背景。请改用 Swing 计时器。请参阅How to Use Swing Timers
  3. 在事件调度线程上运行所有 Swing 应用程序。请参阅Initial Threads

这是用这三点重构的代码

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Frame1 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final JFrame frame = new JFrame();
frame.getContentPane().setBackground(
new Color(0, 0, 0));
Timer timer = new Timer(10, new ActionListener() {
int num = 0;
public void actionPerformed(ActionEvent e) {
if (num > 255) {
((Timer) e.getSource()).stop();
} else {
frame.getContentPane().setBackground(
new Color(num, num, num));
num++;
}
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
timer.start();
}
});
}
}

关于java - 如何重新加载 JFrame - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25620975/

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