简体   繁体   English

如何从 Main 刷新 JApplet?

[英]How can I refresh a JApplet from Main?

I am trying to learn 2D graphics.我正在尝试学习 2D 图形。 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.为了让它们刷新,我最终在paint方法中插入了repaint(1000),但我知道它有时会在不需要的时候进行绘制。

    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. Main 有一个对paint的引用,因为它创建了小程序,但f.repaint()似乎没有做任何事情。 (If I comment out the repaint() in paint, it does not update). (如果我在 Paint 中注释掉 repaint(),它不会更新)。 What am I doing wrong?我究竟做错了什么?

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这些都展示了 Swing 中的动画原理和自定义图形

您为 JFrame 而不是 JApplet 编码,尽管它们都可以实现 WindowListener 并且它们都可以访问 paint(Graphics g) 方法。

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

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