日期:2014-05-20 浏览次数:20711 次
public class MainFrame extends JFrame implements KeyListener{
int x = 0;
int y = 0;
public void paint(Graphics g){
g.setColor(Color.red);
g.drawRect(x, y, 40, 30);
}
public void update(Graphics g) {
paint(g);
}
public void LunchFrame(){
this.setResizable(false);
this.setSize(512, 600);
this.setBackground(Color.black);
this.setTitle("飞机大战暴爽版! xsx");
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setVisible(true);
this.addKeyListener(this);
new Thread(new PaintThread()).start();
}
public static void main(String[] args){
MainFrame mframe = new MainFrame();
mframe.LunchFrame();
}
private class PaintThread implements Runnable {
public void run() {
while(true) {
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
int keyCode = e.getKeyCode();
//后面会添加具体按键匹配
switch (keyCode) {
case KeyEvent.VK_SPACE:
break;
case KeyEvent.VK_A:
System.out.println("xxsx");
x -= 1;
break;
case KeyEvent.VK_D:
x += 1;
break;
case KeyEvent.VK_W:
y -= 1;
break;
case KeyEvent.VK_S:
y += 1;
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainPanel extends JPanel implements KeyListener {
private static final long serialVersionUID = 1147736728548400926L;
int x = 0;
int y = 0;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.drawRect(x, y, 40, 30);
}
public static void main(String[] args) {
JFrame f = new JFrame();
MainPanel mPanel = new MainPanel();
f.add(mPanel);
f.setResizable(false);
f.setSize(512, 600);
f.setBackground(Color.black);
f.setTitle("飞机大战暴爽版! xsx");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setVisible(true);
mPanel.addKeyListener(mPanel);
mPanel.start();
mPanel.requestFocus();