我创建了一个程序,在JFrame中有一个绿色方块,然后按下键#34; A"和" D"向左和向右移动(A =左,D =右)。但是当我运行程序时,按下A / D键时,方块不会移动。我试图检查我的代码是否有错,但我找不到任何错误。如果你能告诉我我的代码哪里出错了那就太棒了!!
import java.awt.event.*;
import java.awt.*;
import java.util.Scanner;
import javax.swing.*;
public class four extends JPanel implements ActionListener,KeyListener {
private static final long serialVersionUID = 1L;
static int x=0, y=0;
static int x1=0, y1=0;
static int width=500,height=600;
static JFrame f;
boolean left, right;
boolean playGame = true;
public void paintComponent (Graphics g){
g.setColor(Color.black);
g.drawRect(x,100,700,100);
g.drawRect(x,200,700,100);
g.drawRect(x,300,700,100);
g.drawRect(x,400,700,100);
g.drawRect(x,500,700,100);
g.drawRect(x,600,700,100);
g.drawRect(x,700,700,100);
g.drawRect(100,100,100,700);
g.drawRect(200,100,0,700);
g.drawRect(300,100,0,700);
g.drawRect(400,100,0,700);
g.drawRect(500,100,0,700);
g.drawRect(600,100,0,700);
g.setColor(Color.green);
g.fillRect(x1, y1, 100, 100);
}
public static void main(String[] args){
four q=new four();
JFrame f=new JFrame("Connect 4");
q.init();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(q);
f.setSize(700,820);
f.setVisible(true);
}
public void init (){
this.addKeyListener(this);
setFocusable(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (left==true)
{
x1=x1-100;
}
if (right==true)
{
x1=x1+100;
}
f.repaint();
System.out.println(x1);
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if (e.getKeyCode()==KeyEvent.VK_A){
left=true;
}
if (e.getKeyCode()==KeyEvent.VK_D){
left=true;
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
if (e.getKeyCode()==KeyEvent.VK_A){
left=false;
}
if (e.getKeyCode()==KeyEvent.VK_D){
right=false;
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
答案 0 :(得分:1)
super.paintComponent
KeyListener
上的键绑定API,它解决了KeyListener
遭受的焦点相关问题。有关详细信息,请参阅How to Use Key Bindings actionPerformed
方法?我想你想仔细看看How to use Swing Timers