当前位置: 代码迷 >> J2SE >> Swing:为什么repaint()并没有调用paintComponent方法,该如何解决
  详细解决方案

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

热度:340   发布时间:2016-04-24 02:27:48.0
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。