日期:2014-05-20  浏览次数:20679 次

关于repaint()函数的疑惑。
我的这段代码,为什么在主函数当中调用fun()函数,就能够达到我想要的效果,能一步一步显示出执行过程。
而当点击按钮时,同样是调用fun()函数,为什么就没有显示出执行过程呢???
具体执行请运行代码。
我觉得应该是repaint()函数内部执行原理不太了解。或者是那个Thread.sleep(1000)的问题???
总之,我是个初学者,请大家指教。
代码如下:
Java code

public class Test extends JFrame implements ActionListener {

    public static void main(String[] args)
    {
        Test t = new Test();
        t.fun();
        System.out.println("End of Main");
    }

    int    x, y;
    Button but;
    
    public Test() {
        setBounds(400, 100, 350, 200);
        this.setLayout(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        but = new Button("OK");
        but.setSize(40, 40);
        add(but);
        but.addActionListener(this);
        x = y = 50;
        setVisible(true);
    }
    public void paint(Graphics g) {
        System.out.println("call paint()");
        super.paint(g);
        g.fillOval(x, y, 9, 9);
    }
    public void fun() {
        for (int i = 0; i < 5; i++) {
            x += 20;
            repaint();
            try   { Thread.sleep(1000); }
            catch (InterruptedException e) { e.printStackTrace(); }
        }
    }
    
    public void actionPerformed(ActionEvent e) {
        fun();
    }
}




------解决方案--------------------
探讨
为什么改成paint()就没有以前的毛病了呢???

------解决方案--------------------
Java code
public class Test extends JFrame implements ActionListener {

    public static void main(String[] args)
    {
        Test t = new Test();
        t.fun();
        System.out.println("End of Main");
        for (int i=0; i<100; i++) { //主线程循环测试,看看主线程是否影响Swing线程
            System.out.println("main" + i);
            try {Thread.sleep(1000);} catch (Exception e) {}
        }
    }

    int    x, y;
    Button but;
    
    public Test() {
        setBounds(400, 100, 350, 200);
        this.setLayout(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        but = new Button("OK");
        but.setSize(40, 40);
        add(but);
        but.addActionListener(this);
        x = y = 50;
        setVisible(true);
    }
    public void paint(Graphics g) {
        System.out.println("call paint()");
        super.paint(g);
        g.fillOval(x, y, 9, 9);
    }
    public void fun() {
        for (int i = 0; i < 5; i++) {
            x += 20;
            repaint();
            try   { Thread.sleep(1000); }
            catch (InterruptedException e) { e.printStackTrace(); }
        }
    }
    
    public void actionPerformed(ActionEvent e) {
        new Thread() { //用线程来执行,看看该线程是否影响Swing线程
            public void run() {
                fun();
            }
        }.start();
    }
}