本文共 1200 字,大约阅读时间需要 4 分钟。
该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI {
public static void main(String[] args) {
GameFrame myFrame=new GameFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
}
class GameFrame extends JFrame{
public static final int WIDTH=500;
public static final int HEIGHT=300;
public GameFrame(){
setSize(WIDTH,HEIGHT);
setResizable(false);
Container contentPane=getContentPane();
GamePanel myPanel=new GamePanel();
contentPane.add(myPanel);
}
}
class GamePanel extends JPanel{
int x=50,y=50;
public static final int XSPEED=5;
public static final int YSPEED=5;
public GamePanel(){
addKeyListener(new KeyMonitor());
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Color c=g.getColor();
g.setColor(Color.RED);
g.fillOval(x,y,20,20);
g.setColor(c);
}
public class KeyMonitor extends KeyAdapter{
public void keyPressed(KeyEvent e){
int key=e.getKeyCode();
switch(key){
case KeyEvent.VK_LEFT:
x-=XSPEED;
break;
case KeyEvent.VK_RIGHT:
x+=XSPEED;
break;
case KeyEvent.VK_UP:
y-=YSPEED;
break;
case KeyEvent.VK_DOWN:
y+=YSPEED;
break;
}
repaint();
}
public void keyReleased(KeyEvent e){
}
}
}
转载地址:http://xqudv.baihongyu.com/