import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.security.KeyException;import javax.swing.JFrame;public class TankClient extends Frame {
int x=50,y=50;

public void paint(Graphics g) {
Color c=g.getColor();
g.setColor(Color.BLUE);
g.fillOval(x, y, 30,30 );
g.setColor(c);

y+=5;

}
private static final int Game_HIGHT=600;
private static final int Game_WIDTH=600;

public void lauchFrame(){
this.setBounds(200, 20, Game_WIDTH, Game_HIGHT);


this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);

}

});
this.setTitle("Tankwar");
this.setResizable(false);
this.setBackground(Color.GREEN);
this.addKeyListener(new keyMonitor());
setVisible(true);
// validate();
Thread th=new Thread(new PiantThread());
th.start();

}

public static void main(String arg[]){
TankClient tc=new TankClient();
tc.lauchFrame();

}
private class keyMonitor extends KeyAdapter{

@Override
public void keyReleased(KeyEvent e) {
int key=e.getKeyCode();
switch (key){
case KeyEvent.VK_LEFT :
     y+=5;
     repaint();
     break;
}
}


}
public class PiantThread implements Runnable{ @Override
public void run() {
while(true){
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {

e.printStackTrace();
}
}

}

}
}
  把代码复制下来 运行下 后吧继承 Frame 换成JFrame 会发现很不一样!背景不能改了!请高手指教!谢谢!

解决方案 »

  1.   

    问题处在paint(Graphics g)这个上
    使用JFrame时要先调用其父对象也就是java.awt.Frame的paint方法,
    super.paint(Graphics g);
    这样就OK了.
      

  2.   

    zerojetlag
    发现JFrame与Frame的paint()有一点区别JFrame里面repaint时背景不会重绘,Frame背景会重绘,要在JFrame里重绘背景,就要调用super.paint(Graphics g);
      

  3.   

                这是java 的api文档里面的话 update public void update(Graphics g) Just calls paint(g). This method was overridden to prevent an unnecessary call to clear the background. 就是说他会阻止背景重绘,repaint是先调用update 然后paint 所以要在repaint里调用super.paint()