简体   繁体   English

密钥侦听器无法正常工作

[英]the keylistener is not working

I'm really desperate. 我真的很绝望。 I've tried all the tips I could find, searched days in the internet and I still can't understand why can't my code work. 我尝试了所有可以找到的技巧,在互联网上搜索了几天,但我仍然不明白为什么我的代码无法正常工作。 it just doesn't respond to my keyboard input, no error message. 它只是不响应我的键盘输入,没有错误消息。

package drawLine;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.*;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class SnakeJPanel extends JPanel implements KeyListener {
    private static final long serialVersionUID = 7526472295622776147L;


JPanel panelForSnake, snake;

final int WID = 10;
final int HEI = 10;
public static int x1 = 50;
public static int y1 = 50;
public static boolean right = true, left = false, down = false, up = false;
static long millis =System.currentTimeMillis();
static long millisn =System.currentTimeMillis();


public class MyGraphics extends JComponent {

    private static final long serialVersionUID = 1L;

    MyGraphics() {
        setPreferredSize(new Dimension(1000,700));
    }


    public void paintComponent(Graphics g) {
        super.paintComponents(g);
        g.setColor(Color.red);
        g.fillOval(x1, y1, WID, HEI);
    }
}

public JPanel createContentPane (){
    JPanel totalGUI = new JPanel();
    totalGUI.setLayout(null);


    panelForSnake = new JPanel();
    panelForSnake.setBackground(Color.black);
    panelForSnake.setLocation(1,1);
    panelForSnake.setSize(1000,700);
    totalGUI.add(panelForSnake);

    MyGraphics tr = new MyGraphics();
    tr.setLocation(1,50);
    tr.setSize(1000,1000);
    panelForSnake.add(tr);

    return totalGUI;

}
private static void createAndShowGUI() {

    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("Snake Harel");
    //Create and set up the content pane.
    SnakeJPanel demo = new SnakeJPanel();
    frame.setContentPane(demo.createContentPane());

    // The other bits and pieces that make our program a bit more stable.

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1000, 1000);
    frame.setVisible(true);


}
public void keyPressed(KeyEvent e) {
    requestFocusInWindow();
    requestFocus();
    addKeyListener((KeyListener) this);
    setFocusable(true);
    setFocusTraversalKeysEnabled(false);
    int key = e.getKeyCode();

    if ((key == KeyEvent.VK_LEFT) && (!right)) {
        left = true;
        up = false;
        down = false;
    }

    if ((key == KeyEvent.VK_RIGHT) && (!left)) {
        right = true;
        up = false;
        down = false;
    }

    if ((key == KeyEvent.VK_UP) && (!down)) {
        up = true;
        right = false;
        left = false;
    }

    if ((key == KeyEvent.VK_DOWN) && (!up)) {
        down = true;
        right = false;
        left = false;
    }
}
public static void move(boolean l,boolean r,boolean u,boolean d){
    if (r = true){
        millis =System.currentTimeMillis();
        millisn =System.currentTimeMillis();
            while (millisn<millis+20){
                millisn=System.currentTimeMillis();
            }
        ++x1;
    }
    if (l = true){
        millis =System.currentTimeMillis();
        millisn =System.currentTimeMillis();
            while (millisn<millis+20){
                millisn=System.currentTimeMillis();
            }
        --x1;
    }
    if (u = true){
        millis =System.currentTimeMillis();
        millisn =System.currentTimeMillis();
            while (millisn<millis+20){
                millisn=System.currentTimeMillis();
            }
        ++y1;
    }
    if (d = true){
        millis =System.currentTimeMillis();
        millisn =System.currentTimeMillis();
            while (millisn<millis+20){
                millisn=System.currentTimeMillis();
            }
        --y1;
    }
}

public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
         move(left, right, up, down);
         }
    });
}

public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}

} }

I've tried all the tips I could find, searched days in the internet 我尝试了所有可以找到的技巧,在互联网上搜索了几天

Then why are you still attempting to use a KeyListener??? 那么,为什么您仍然尝试使用KeyListener? The better solutions you will find on the forums will always tell you to use Key Bindings. 在论坛上找到的更好的解决方案将始终告诉您使用“键绑定”。

See Motion With the Keyboard for common problems with using a KeyListner and the solutions as well as working examples with Key Bindings which is what you should be using anyway. 有关使用KeyListner和解决方案的常见问题,请参阅“使用键盘运动” ,以及无论如何都应使用的“键绑定”示例。

You're adding the keyListener inside the keyPressed method. 您将在keyPressed方法内添加keyListener。 However, the keyPressed method is never called until the keyListener is added. 但是,在添加keyListener之前,永远不会调用keyPressed方法。 Just add it in the main method or when the GUI is created. 只需将其添加到main方法中或在创建GUI时即可。

private static void createAndShowGUI() {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("Snake Harel");
    //Create and set up the content pane.
    SnakeJPanel demo = new SnakeJPanel();
    frame.setContentPane(demo.createContentPane());
    addKeyListener(this);

    // The other bits and pieces that make our program a bit more stable.

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1000, 1000);
    frame.setVisible(true);
}

Since you're not using all of the keyListener interface I suggest creating a nested class instead and extending the KeyAdapter class. 由于您没有使用所有的keyListener接口,因此建议您创建一个嵌套类,并扩展KeyAdapter类。

public class ActionListener extends KeyAdapter {
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if ((key == KeyEvent.VK_LEFT) && (!right)) {
                left = true;
                up = false;
                down = false;
        }
        if ((key == KeyEvent.VK_RIGHT) && (!left)) {
            right = true;
            up = false;
            down = false;
        }
        if ((key == KeyEvent.VK_UP) && (!down)) {
            up = true;
            right = false;
            left = false;
        }
        if ((key == KeyEvent.VK_DOWN) && (!up)) {
            down = true;
            right = false;
            left = false;
        }
}

Then you'd add the ActionListener class as the key listener. 然后,将ActionListener类添加为键侦听器。

EDIT: Create an instance of the class in the main method, 编辑:在main方法中创建类的实例,

new SnakeJPanel();

Then create a constructor, 然后创建一个构造函数,

private SnakeJPanel() {
    addKeyListener(this);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM