import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.*;
/**
* 画一个小球,可以用上下左右移动它
* @author sony
*
*/
public class demo_4 extends JFrame{
/**
* @param args
*/
MyPanel_4 mp = null;
public static void main(String[] args) {
// TODO Auto-generated method stub
new demo_4();
}
public demo_4()
{
//初始化
mp = new MyPanel_4(10,10);
this.add(mp);
//this.setBounds(300, 300, 400, 300);
this.setSize(400, 300);
this.setVisible(true);
//事件键盘监听
this.addKeyListener(new KeyAdapter()
{
@Override
public void keyPressed(KeyEvent e)
{
int newY = mp.getY();
int newX = mp.getX();
//向上
if(KeyEvent.VK_UP == e.getKeyCode()){
mp.setY(--newY);
}
//向下
else if(KeyEvent.VK_DOWN == e.getKeyCode()){
mp.setY(++newY);
}
//向左
else if(KeyEvent.VK_LEFT == e.getKeyCode()){
mp.setX(--newX);
}
//向右
else if(KeyEvent.VK_RIGHT == e.getKeyCode()){
mp.setX(++newX);
}
mp.repaint();
}
}
);
}
}
class MyPanel_4 extends JPanel
{
private int x=10;
private int y=10;
public MyPanel_4(int x,int y){
this.x = x;
this.y = y;
}
@Override
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.red);
g.fillOval(x, y, 20, 20);
}
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;
}
}
小球往下移动
小球网右边移动
|
|