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

前端 未结 2 479
孤独总比滥情好
孤独总比滥情好 2021-01-14 06:07

I think I need to put some code where the comment is (or maybe use non static method but I am not sure). The main method creates the window and then starts the graphics meth

2条回答
  •  花落未央
    2021-01-14 06:44

    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.

提交回复
热议问题