Search code examples
javaswingpaintgraphics2djapplet

How can I refresh a JApplet from Main?


I am trying to learn 2D graphics. This code below draws a couple of spinning wheels. To get them to refresh, I finally inserted the repaint(1000) in the paint method, but I know that this paints at times when it does not have to.

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        for(int angle=0; angle<360; angle+=90){
            g2.setColor(blue);
            g2.fillArc(100,100,200,200,theta1 + angle,45);
            g2.setColor(red);
            g2.fillArc(100,100,200,200,theta1 + angle + 45,45);
        }

        for(int angle=0; angle<360; angle+=30){
            g2.setColor(green);
            g2.fillArc(250,250,250,250,angle + theta2,15);
            g2.setColor(yellow);
            g2.fillArc(250,250,250,250,angle + theta2 + 15,15);
        }

//        repaint(1000);
   }

    public static void main(String s[]) {
        JFrame f = new JFrame("ShapesDemo2D");
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);}
        });
        JApplet applet = new ShapesDemo2D();
        f.getContentPane().add("Center", applet);
        applet.init();
        f.pack();
        f.setSize(new Dimension(800,800));
        f.setVisible(true);

        while(true) {
            theta2 += 5;
            theta1 -= 2;

            f.repaint(1000);

            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }

What I would really like to do is have it refresh after I have made a change. Main has a reference to paint since it created the applet, but the f.repaint() does not appear to do anything. (If I comment out the repaint() in paint, it does not update). What am I doing wrong?


Solution

  • It would be to your advantage to have a read through

    I would also have a look at

    Which all show animation principles and custom graphics in Swing