繁体   English   中英

Java Swing基本动画问题

[英]Java Swing basic animation issue

我刚刚开始学习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);
}

}
}

矩形显示在屏幕上,但不会每50毫秒重新绘制成较小的尺寸

在进行自定义绘画时,基本代码应为:

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

    //  add custom painting code
}

如果您不清除背景,则保留旧画。 因此,画一些较小的东西不会有任何影响。

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

  1. 您应该改为重新绘制整个JFrame (或重新绘制图形的JPanel)。
  2. 您不必两次调用x++ ,而只需执行x+=2

将您的代码更改为此(有效,我也修复了缩进):

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 += 2) {
            frame.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);
        }

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM