import javax.swing.*; import java.awt.event.*; import java.awt.*; class TouChaCol{ int x = 70; int y = 70; public static void main(String [] args){ TouChaCol ch = new TouChaCol(); ch.go(); } class Panel extends JPanel{ public void paintComponent(Graphics g){ g.setColor(Color.white); g.fillRect(0, 0, this.getWidth(), this.getHeight()); g.setColor(Color.orange); g.fillOval(x, y, 40, 40); } } public void go(){ JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Panel panel = new Panel(); frame.getContentPane().add(panel); frame.setSize(700,700); frame.setVisible(true); for(int i=0;i<300;i++){ x++; y++; panel.repaint(); try{ Thread.sleep(50); }catch(Exception ex){ } } } }
用到内部类,内部类可直接使用到外部类的实例变量