代码如下
package cn.gui;import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;public class Ball extends JFrame
{ MyPanel mp; public static void main(String[] args)
{
new Ball();
} Ball()
{
mp = new MyPanel(10, 10);
// this.addKeyListener(mp);
this.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_UP)
mp.setY(mp.getY() - 10);
if (e.getKeyCode() == KeyEvent.VK_DOWN)
mp.setY(mp.getY() + 10);
if (e.getKeyCode() == KeyEvent.VK_LEFT)
mp.setX(mp.getX() - 10);
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
mp.setX(mp.getX() + 10);
mp.repaint();
}
});
this.add(mp);
this.setBounds(200, 200, 400, 300);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}class MyPanel extends JPanel // implements KeyListener
{
int x, y; public MyPanel(int x, int y)
{
super();
this.x = x;
this.y = y;
} public int getX()
{
return x;
} public void setX(int x)
{
this.x = x;
} public int getY()
{
return y;
} public void setY(int y)
{
this.y = y;
} public void paint(Graphics g)
{
super.paint(g);
g.fillOval(x, y, 10, 10);
}
// public void paintComponent(Graphics g)
// {
// super.paintComponent(g);
// g.fillOval(x, y, 10, 10);
// }
}
当使用paint时,移动小球会留下痕迹,最小化或者改变窗口后痕迹就会消失,这是为什么?使用paintComponent确很正常,我们老师讲的时候使用的paint没问题,我运行确有问题绘画