画一个小球怎么就调用了paint方法了呢(我并没有调用他)
package com.test;import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Ball extends JFrame{
MyPanel1 mp=null;
public static void main(String[] args) {
// TODO Auto-generated method stub
Ball ball=new Ball();
}
public Ball()
{
mp=new MyPanel1();
this.add(mp);
//注册监听
this.addKeyListener(mp);
this.setSize(300,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
//定义自己的面板
class MyPanel1 extends JPanel implements KeyListener
{
int x=10;
int y=10;
public void paint(Graphics g) //系统会调用父类默认的方法,实现重画功能
{
super.paint(g);
g.fillOval(x, y, 20, 20);
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
//System.out.println("anxia"+(char)e.getKeyCode());
if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
y++;
}else if(e.getKeyCode()==KeyEvent.VK_UP)
{
y--;
}else if(e.getKeyCode()==KeyEvent.VK_LEFT)
{
x--;
}else if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{
x++;
}
//调用repaint()函数 ,来重绘界面
this.repaint();
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}