gpt4 book ai didi

Java重绘()困惑

转载 作者:行者123 更新时间:2023-11-30 10:19:49 29 4
gpt4 key购买 nike

我有一个程序可以打开一个窗口并快速改变背景颜色并随机弹出矩形和椭圆形。我的代码有效,但我不知道为什么,因为我没有在我的代码中调用 repaint() 函数。当我使用我个人的 update() 函数包含 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();
}
}
}

谢谢,普拉纳夫

最佳答案

内部某处的 setBackground 方法会导致框架重新绘制自身,这会再次调用您的 paintComponent 并再次调用 setBackground。这会创建无限循环。删除 setBackground 行,它应该按预期工作。如果您想更改面板的背景,请尝试在 paintComponent 方法之外设置它,或者在整个面板上绘制一个所需颜色的矩形。

关于Java重绘()困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48443472/

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