如何将 KeyListener 与 JFrame 一起使用?
所以,我试图用()使矩形移动,每当我尝试按键时,矩形都不会移动。KeyEvent
KeyListener
矩形被绘制,但每当我按和键时,没有任何反应。我有两个类,一个是我的主类,带有keyEvents和frame,另一个,绘制矩形并持有移动矩形的函数。left
right
这是我的代码:
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class mainFrame extends JFrame implements KeyListener{
mainDraw Draw = new mainDraw();
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_D){
Draw.moveRight();
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {}
public mainFrame()
{
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public static void main(String[] args) {
mainFrame M1 = new mainFrame();
mainDraw Draw = new mainDraw();
JFrame frame = new JFrame("Square Move Practice");
//frame
frame.setVisible(true);
frame.setResizable(false);
frame.setSize(600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(Draw);
}
}
现在是第二类:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
public class mainDraw extends JComponent{
public int x = 50;
public int y = 50;
public void paint(Graphics g){
g.drawRect(x, y, 50, 50);
g.fillRect(x, y, 50, 50);
g.setColor(Color.BLACK);
}
public void moveRight()
{
x = x + 5;
y = y + 0;
repaint();
}
}
请告诉我如何移动矩形。提前致谢!