日期:2014-05-20 浏览次数:20800 次
---javax.swing 类 JComponent:
---从类 java.awt.Component 继承的方法repaint()
API描述:repaint
public void repaint()重绘此组件。
如果此组件是轻量级组件,则此方法会尽快调用此组件的 paint 方法。否则此方法会尽快调用此组件的 update 方法。
public class Bounce {//这是执行入口
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run(){
JFrame frame = new BounceFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
public class BounceFrame extends JFrame {
private final static long serialVersionUID = 2L;
public BounceFrame()
{
setTitle("Bounce");
setSize(Default_WIDTH,Default_HEIGHT);
comp = new BallComponent();
add(comp, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
addButton(buttonPanel , "Start" , new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
addBall();
}
});
addButton(buttonPanel , "Close" , new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
add(buttonPanel , BorderLayout.SOUTH);
}
private void addButton(Container c, String title, final ActionListener listener)
{
JButton button = new JButton(title);
c.add(button);
button.addActionListener(listener);
}
private void addBall()
{
try{
Ball ball = new Ball();
comp.add(ball);//这一步是添加并且重绘一个球
for(int i=0 ; i <= STEPS ; i++ )
{
ball.move(comp.getBounds());
// comp.paint(comp.getGraphics());
comp.repaint(); //此时不执行移动重绘,这就是问题点
// comp.update(comp.getGraphics());
Thread.sleep(DELAY);
}
}catch(InterruptedException err){}
}
private BallComponent comp ;
private final static int Default_WIDTH = 450;
private final static int Default_HEIGHT = 300;
private final static int STEPS = 1000;
private final static int DELAY = 3;
}
public class Ball {