我在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("");
}
}
}
答案 0 :(得分:1)
这是你用这三点重构的代码
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();
}
});
}
}
答案 1 :(得分:0)
像这样,只会创建一个框架,您可以调整颜色并进行所需的刷新。
package frames;
import java.awt.Color;
import javax.swing.*;
public class Frame1 {
public static void main(String[] args)
{
int num = 0;
JFrame frame = new JFrame();
frame.setSize(400,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("");
while (num<255)
{
num +=1;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Here, we can safely update the GUI
// because we'll be called from the
// event dispatch thread
frame.getContentPane().setBackground(new Color(num,num,num));
frame.pack();
frame.repaint();
}
}
}
});
}
}
}
也许我只是混淆了}但你应该知道如何做到这一点