gpt4 book ai didi

Java Swing基本动画问题

转载 作者:行者123 更新时间:2023-12-02 04:25:29 26 4
gpt4 key购买 nike

我刚刚开始学习 GUI 和 Swing,并决定编写一个我在教科书中找到的程序来显示一个彩色矩形,并使其在屏幕上看起来尺寸正在缩小。

下面是我编写的代码,我的问题是矩形显示在屏幕上,但没有每 50 毫秒重新绘制为较小的尺寸。谁能指出我哪里出了问题?

非常感谢

import javax.swing.*;
import java.awt.*;

public class Animate {

int x = 1;
int y = 1;

public static void main(String[] args){

Animate gui = new Animate();
gui.start();

}

public void start(){

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Rectangles rectangles = new Rectangles();

frame.getContentPane().add(rectangles);
frame.setSize(500,270);
frame.setVisible(true);

for(int i = 0; i < 100; i++,y++,x++){

x++;
rectangles.repaint();

try {
Thread.sleep(50);
} catch (Exception ex) {
ex.printStackTrace();
}

}

}





class Rectangles extends JPanel {

public void paintComponent(Graphics g){
g.setColor(Color.blue);
g.fillRect(x, y, 500-x*2, 250-y*2);
}

}
}

最佳答案

the rectangle displays on the screen, but is not repainted to a smaller size every 50ms

进行自定义绘画时,基本代码应该是:

protected void paintComponent(Graphics g)
{
super.paintComponent(g); // to clear the background

// add custom painting code
}

如果您不清除背景,那么旧画就会保留下来。所以画一些较小的东西不会有什么不同。

为了获得更好的代码结构,x/y 变量应在 Rectangles 类中定义。然后,您应该创建一个类似 decreaseSize() 的方法,该方法也在您的 Rectangles 类中定义。此代码将更新 x/y 值,然后调用自身重绘。因此,您的动画代码将仅调用 decreaseSize() 方法。

关于Java Swing基本动画问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32232466/

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