错误是在第84行! 说
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;public class MoveBall
{
public static void main(String [] args)
{
BallFrame b=new BallFrame();
b.setVisible(true);
}
}class BallFrame extends JFrame
{
JPanel jp=new JPanel();
public BallFrame()
{
this.setBounds(100,150,400,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel con=(JPanel)this.getContentPane();

jp.setBackground(Color.black);
con.add(jp);
new Ball(jp).start();
}
}class Ball extends Thread
{
int r=0;
int moveX=2;
int moveY=2;
int ballX=50;
int ballY=50;
int WIDTH=10;
JPanel jp=new JPanel();
public Ball(JPanel jp)
{
this.jp=jp;
System.out.println("jpjp");
jp.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
switch(e.getKeyCode())
{
case KeyEvent.VK_LEFT:r=0;System.out.println("VK_LEFT");break;
case KeyEvent.VK_RIGHT:r=1;System.out.println("VK_RIGHT");break;
case KeyEvent.VK_UP:r=2;System.out.println("VK_UP");break;
case KeyEvent.VK_DOWN:r=3;System.out.println("VK_DOWN");break;
default:System.out.println("others");
}
}
});
jp.setFocusable(true);

}

public void move()
{
Graphics g=jp.getGraphics();
g.setXORMode(jp.getBackground());//错误在这里!!!

g.fillOval(ballX,ballY,WIDTH,WIDTH); switch(r)
{
case 0:ballX+=-moveX;
case 1:ballY+=moveX;
case 2:ballY+=-moveX;
case 3:ballY+=moveX;
}
g.fillOval(ballX,ballY,WIDTH,WIDTH);
g.dispose();
}

public void run()
{
Graphics g=jp.getGraphics();
if(jp==null)
System.out.println("null");
g.setXORMode(jp.getBackground());
g.dispose();
while(true)
{
this.move();
try
{
Thread.sleep(10);
}
catch(Exception ex){}
}
}
}

解决方案 »

  1.   

    修改一下你的BallFrame定义class BallFrame extends JFrame
    {
    JPanel jp=new JPanel();
    public BallFrame()
    {
    this.setBounds(100,150,400,300);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel con=(JPanel)this.getContentPane();

    jp.setBackground(Color.black);
    con.add(jp);
    new Ball(jp).start();
    }
    }改为:class BallFrame extends JFrame {
    JPanel jp = new JPanel(); public BallFrame() {
    this.setBounds(100, 150, 400, 300);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel con = (JPanel) this.getContentPane(); jp.setBackground(Color.black);
    con.add(jp);
    this.setVisible(true);//增加这行代码,显示之后才能取的到graphics
    new Ball(jp).start();
    }
    }