我正在用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("");
}
}
}
最佳答案
您只需要使用一帧(您将创建255帧)
不要使用while循环来尝试更改背景。请改用Swing计时器。见How to Use Swing Timers
在事件调度线程上运行所有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();
}
});
}
}