我想在JFrame
框周围移动一个圆形图形并决定添加一个KeyListener
,但我似乎无法让它工作。
package keyBoardInput;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Window;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class window extends JFrame implements KeyListener {
Rectangle rect;
//KeyListener keyListener;
public void init() {
this.addKeyListener(this);
setFocusTraversalKeysEnabled(true);
requestFocus(true);
rect = new Rectangle(0,0,100,100);
}
public window() {
super("Title bar");
setSize(800,600);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setFocusTraversalKeysEnabled(true);
requestFocus(true);
setFocusable(true);
//addKeyListener(keyListener);
}
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.cyan);
g2.fillRect(0,0,800,600);
g2.setColor(Color.orange);
g2.fillOval(0,0,100,100);
}
public void keyPressed(KeyEvent e) {
System.out.println("test");
int key = e.getKeyCode();
if (key == KeyEvent.VK_W) {
rect.setLocation(rect.x + 0, rect.y + 10);
}
if (key == KeyEvent.VK_S) {
rect.setLocation(rect.x - 0, rect.y - 10);
}
if (key == KeyEvent.VK_A) {
rect.setLocation(rect.x - 10, rect.y + 0);
}
if (key == KeyEvent.VK_D) {
rect.setLocation(rect.x + 10, rect.y + 0);
}
repaint();
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}
答案 0 :(得分:4)
如果你在这里搜索类似的问题,答案几乎总是:
但还有......