How do I re run the paint method so the JPanel is animated?

和自甴很熟 提交于 2019-12-01 09:41:56

Use a Swing Timer to call repaint(). Also, override paintComponent() in a JPanel, rather than paint().

Something like this:

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

public class PaintTest extends JPanel{

    boolean blueSqr = false;

    PaintTest() {
        setPreferredSize(new Dimension(100,25));
        ActionListener al = new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                blueSqr = !blueSqr;
                repaint();
            }
        };
        Timer timer = new Timer(1000,al);
        timer.start();
    }

    public void paintComponent(Graphics g) {
        Color c = (blueSqr ? Color.BLUE : Color.RED);
        g.setColor(c);
        g.fillRect(10, 10, 10, 10);
    }

    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame theWindow = new JFrame("Window");
                theWindow.getContentPane().add(new PaintTest());
                createWindow(theWindow);
            }
        });
    }

    public static void createWindow(JFrame theWindow){
        theWindow.pack();
        theWindow.setLocationByPlatform(true);
        theWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        theWindow.setVisible(true);
    }
}

There were other improvements I could not be bothered documenting (code speaks louder than words). If you have any questions (check the docs first, then) ask.

mKorbel

your issues are

1) by calling Thread.sleep(int) in the Swing related code, never do that, for delaying in Swing (there are lots of topics about why not use sleep in programing languages ...) use Swing Timer

2) your JPanel doesn't returns any XxxSize

3) for Swing use paintComponent(), only if you have got really important reasons then use method paint() more about repaint and animating Graphics in the 2D Graphics tutorial

4) Swing GUI should be built in the Event Dispatch Thread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!