繁体   English   中英

Java Swing尝试制作带有矩形的小动画

[英]Java Swing Try to make a little animation with rectangle

我尝试做一个迷你游戏,但首先我要学习动画:)这将是一个2D游戏。 所以我的问题是,当我尝试制作动画时,如果我只是尝试绘制一个矩形的工作(我做了很多代码但没有工作:()它没有工作。

有人可以帮助我修复它或添加一些提示,我如何尝试做到这一点。

public class Window extends JPanel implements ActionListener {

    Timer tm = new Timer(5 , this);

    int x2 = 0 , velX = 2;

    static int x= 500;
    static int y= 500;

    public void paintComponent(Graphics g){

        super.paintComponent(g);

        g.setColor(Color.RED);
        g.fillRect(x2, 30, 30, 30);

        tm.start();

    }

    public Window(){

        JFrame f = new JFrame();
        f.pack();
        f.setTitle("Game");
        f.setSize(x,y);
        f.setVisible(true);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
    }

    /*public void paint(Graphics g){


        Graphics2D g2d = (Graphics2D) g;
        Rectangle rect = new Rectangle(50, 50, 50, 50);


        g2d.translate(25, 25);
        g2d.rotate(Math.toRadians(45));
        g2d.draw(rect);
    }*/

    public static void main(String [] args) throws InterruptedException{
        Game g = new Game();
        g.setName("Test");
        System.out.println(g.getName());
        g.setScore();
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        x2 = x2 + velX;
        repaint();

    }

}

您的代码工作正常,除非您忘记将Component(您命名为Window )添加到Container(在本例中为JFrame )中。 为此,添加f.add(this); Window()构造函数的末尾。

看一下秋千组件和容器以获取更多信息。

我还建议您看一看标准Java-AWT中的Double-bufferGame循环!

暂无
暂无

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

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