我编写了一个程序,其中JFrame中有一个绿色方块,然后按“ 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

}

最佳答案

执行任何自定义绘画之前,请致电super.paintComponent
KeyListener上使用键绑定API,可以解决KeyListener遇到的与焦点有关的问题。有关更多详细信息,请参见How to Use Key Bindings
从事件调度线程的上下文中初始化UI。有关更多详细信息,请参见Initial Threads
什么叫actionPerformed方法?我认为您想进一步了解How to use Swing Timers

07-24 15:48