所以我创建了这个程序,我试图根据箭头键移动蓝色方块。但是,我遇到了一些问题(正如您将在代码中看到的那样)。我已经在网上搜索了一个答案,但没有取得胜利。 这是我的问题:
我可能只是遇到了一些逻辑问题,或者有一种更简单的方法可以让Java做到这一点。如果是,请留下明确的解释。 请忽略我在整个地方记下的随机记录。
//graham
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
class Arrows extends JPanel implements KeyListener {
private int c = 0, c1 = 0;
private int x = 250;
private int y = 250;
private int cx = 0; //change in x
private int cy = 0; //change in y
private static ArrayList<Integer> keys = new ArrayList<Integer>();
public Arrows() {
this.setPreferredSize(new Dimension(500, 500));
addKeyListener(this);
}
public void addNotify() {
super.addNotify();
requestFocus();
}
public void paintComponent(Graphics g) {
//*********
//here need to repaint according to the key
//need to update to make so can press (and hold) multiple different keys at once
//*********
g.setColor(Color.WHITE);
g.fillRect(x, y , 20, 20);
//for(int i = 0; i < keys.size(); i++){ //********> only want to handle one at a time
//handle the key
//***Should move this to somewhere else, so repaint after update stuff in keyPressed
//}
//x += cx;
//y += cy;
g.setColor(Color.BLUE);
g.fillRect(x + cx, y + cy, 20, 20);
}
public void keyPressed(KeyEvent e) {
//******
//need to add to the keyList here
//might want to use bitset
//******
//keys.add(e.getKeyCode());
//**********************************
//c = keys.get(0);
c = e.getKeyCode();
switch(c){
case 37:
//left arrow
cx -= 3;
//keys.remove(0);
break;
case 38:
// up arrow
cy -= 3;
//keys.remove(0);
break;
case 39:
//right arrow
cx += 3;
//keys.remove(0);
break;
case 40:
//down arrow
cy += 3;
//keys.remove(0);
break;
}
//**********************************
repaint();
}
public void keyReleased(KeyEvent e) {
//****
//here need to remove key fromt he list, and may want to fix teleportation..
//****
//set the change values to 0
c1 = e.getKeyCode();
switch(c1){
case 37:
//left arrow
cx = 0;
break;
case 38:
// up arrow
cy = 0;
break;
case 39:
//right arrow
cx = 0;
break;
case 40:
//down arrow
cy = 0;
break;
}
repaint();
}
public void keyTyped(KeyEvent e) {
}
public static void main(String[] s) {
JFrame f = new JFrame();
f.getContentPane().add(new Arrows());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
//need to null out keys
keys.add(65);
//here want to update every time through constant time accoridng to the keypressed and ereleased crap
//repaint();
}
}
答案 0 :(得分:-1)
一些通用编程评论:
不要使用KeyListener。 Swing旨在与Key Bindings
一起使用。有关更多信息和工作示例,请参阅Motion Using the Keyboard。