首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

Swing:为什么repaint()并没有调用paintComponent方法,该如何解决

2012-01-15 
Swing:为什么repaint()并没有调用paintComponent方法这个程序想要画两个小球,一个平抛,一个自由落体。为什

Swing:为什么repaint()并没有调用paintComponent方法
这个程序想要画两个小球,一个平抛,一个自由落体。为什么在62行的repaint方法,并没有进入paintComponent()方法中。
请高手指教!

Java code
package org.net;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.awt.geom.Ellipse2D;public class BallFrame extends JFrame{    JPanel downPanel;    JButton startButton;    MyPanel upPanel;    Ellipse2D.Double d1 ;    Ellipse2D.Double d2 ;    long t;    long begin;    double x;    double y;    public BallFrame(){        setSize(300,400);        downPanel = new JPanel();        startButton = new JButton("start");        startButton.addActionListener(new ActionListener(){            public void actionPerformed(ActionEvent event){                MyThread t = new MyThread();                begin = System.currentTimeMillis();                t.start();            }        });        downPanel.add(startButton);        add(downPanel,BorderLayout.SOUTH);        upPanel = new MyPanel();        d1 = new Ellipse2D.Double(0,0,15,15);        d2 = new Ellipse2D.Double(0,0,15,15);        upPanel.addBall(d1,d2);    }    public static void main(String[] args) {        BallFrame f = new BallFrame();        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        f.setVisible(true);    }    class MyPanel extends JPanel{        Ellipse2D.Double d1 ;        Ellipse2D.Double d2 ;        public void paintComponent(Graphics g){   //???没有被调用            super.paintComponent(g);            System.out.println("===进入paint方法===");            Graphics2D g2 = (Graphics2D)g;            g2.fill(d1);            g2.fill(d2);        }        public void addBall(Ellipse2D.Double d1,Ellipse2D.Double d2){            this.d1 = d1;            this.d2 = d2;        }    }    class MyThread extends Thread{        public void run(){            for(int i=0;i<1000;i++){                t = (System.currentTimeMillis()-begin)/1000;                x = 26*t;                y = 0.5 * 9.8 * Math.pow(t, 2);                System.out.println(x+":"+y);                repaint();   //????为什么调用repaint方法不能进入paintComponent方法呢?                try{                    Thread.sleep(100);                }                catch(Exception e){                                    }            }        }    }}


[解决办法]
upPanel 根本没添加到frame的contentPane。

热点排行