我正在尝试制作一个背景随时间变化缓慢的JFrame。 这是我的代码:
public class RainbowWindow extends Applet implements ActionListener {
private static final long serialVersionUID = 1L;
public void paint(Graphics g) {
Timer timer = new Timer(1000, this);
timer.start();
}
@Override
public void actionPerformed(ActionEvent e) {
Color color = new Color(((int) Math.random()), ((int) Math.random()), ((int) Math.random()), 255);
setBackground(color);
}
}
但我得到的只是一个黑屏
答案 0 :(得分:2)
Timer
中创建paint
,每次都需要绘制绘画,并且通常需要快速连续绘制。有关绘画如何在Swing paint
和JFrame
等顶级容器的Applet
,它们不是双重缓冲的,它往往不会导致问题的结束,最好从一些开始一种组件并将其添加到您想要的任何容器中JFrame
!= Applet
Math.random
返回0
和1
之间的值,Color
期望0
- 255
例如
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int red = (int)(Math.random() * 255);
int green = (int)(Math.random() * 255);
int blue = (int)(Math.random() * 255);
Color color = new Color(red, green, blue, 255);
setBackground(color);
}
});
timer.start();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
答案 1 :(得分:1)
您应该延长JApplet
(不是Applet
),并添加一个组件来设置颜色,您不应该在Timer
中开始paint
并且,将浮点值转换为int
不会在随机颜色生成中为您提供任何值。像,
public class RainbowWindow extends JApplet implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel panel = new JPanel();
@Override
public void actionPerformed(ActionEvent e) {
Color color = new Color(((int) (Math.random() * 255)),
((int) (Math.random() * 255)),
((int) (Math.random() * 255)), 255);
panel.setBackground(color);
}
public RainbowWindow() {
Timer timer = new Timer(1000, this);
timer.start();
add(panel);
setVisible(true);
}
}
我测试了它,它每秒一次将背景颜色更改为新的随机颜色。