我有一个程序可以打开一个窗口并快速更改背景颜色并随机弹出矩形和椭圆形。我的代码有效,但我不知道为什么,因为我没有在我的代码中调用repaint()函数。当我使用我的个人更新()函数包含repaint()函数时,我没有看到任何明显的变化。这是我的代码:
package epilepsy;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import Math.Math;
/**
*
* @author 21psuby
*/
public class Epilepsy {
JFrame frame;
DrawPanel drawPanel;
Math math = new Math();
int screenW = 800;
int screenH = 700;
int red = math.random(0, 255);
int green = math.random(0, 255);
int blue = math.random(0, 255);
int x = math.random(0, screenW);
int y = math.random(0, screenH);
int w = math.random(0, screenW/2);
int h = math.random(0, screenH/2);
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Epilepsy().go();
}
private void go() {
frame = new JFrame();
drawPanel = new DrawPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setVisible(true);
frame.setSize(screenW, screenH);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
}
class DrawPanel extends JPanel {
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g) {
randomize();
frame.setBackground(new Color(red, green, blue));
randomize();
g.setColor(new Color(red, green, blue));
g.fillRect(x, y, w, h);
randomize();
g.setColor(new Color(red, green, blue));
g.fillRect(x, y, w, h);
randomize();
g.setColor(new Color(red, green, blue));
g.fillRect(x, y, w, h);
randomize();
g.setColor(new Color(red, green, blue));
g.fillOval(x, y, w, h);
randomize();
g.setColor(new Color(red, green, blue));
g.fillOval(x, y, w, h);
randomize();
g.setColor(new Color(red, green, blue));
g.fillOval(x, y, w, h);
}
}
private void randomize() {
red = math.random(0, 255);
green = math.random(0, 255);
blue = math.random(0, 255);
x = math.random(0, screenW);
y = math.random(0, screenH);
w = math.random(0, screenW/2);
h = math.random(0, screenH/2);
}
private void update() {
while (true) {
try {
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
frame.repaint();
}
}
}
谢谢,Pranav
答案 0 :(得分:1)
方法setBackground在某处内部导致帧重绘自己再次调用paintComponent并再次调用setBackground。这会产生无限循环。删除setBackground行,它应该按预期工作。如果要更改面板的背景,请尝试将其设置在paintComponent方法之外,或在整个面板上绘制所需颜色的矩形。