简体   繁体   English

KeyListener未检测到按键

[英]KeyListener not detecting key presses

I'm trying to make a function that hides a JButton when pressing H. I'm using KeyListener to detect if the "H" button has been pressed. 我试图制作一个在按下H时隐藏JButton的函数。我正在使用KeyListener来检测是否已按下“ H”按钮。 Currently I'm trying to detect any button press. 目前,我正在尝试检测是否有任何按钮按下。 The problem is that nothing is detected and nothing happens. 问题是什么也没检测到,什么也没发生。 Code Below is the JPanel. 下面的代码是JPanel。 Ignore the methods since they do not affect the key detection. 忽略方法,因为它们不影响密钥检测。

    public GamePanel(CardLayout cl, JPanel MainPanel, JFrame frame){
    this.cl = cl;
    this.MainPanel = MainPanel;
    DropColor = DropColorRead();
    this.frame = frame;
    this.frame.addKeyListener(new KeyListener(){

        @Override
        public void keyPressed(KeyEvent arg0) {
            System.out.println("asdhuasdiu");

        }

        @Override
        public void keyReleased(KeyEvent arg0) {
            // TODO Auto-generated method stub
        }

        @Override
        public void keyTyped(KeyEvent arg0) {
            // TODO Auto-generated method stub  
        }
    });

    super.setFocusable(true);
    super.requestFocusInWindow();

    // Setting the required space for the array "Rain".
    Rain = new JPanel[amount];

    // Allowing random placement of Object on JPanel.
    super.setLayout(null);
    super.setBackground(BackgroundChange());

    Return.addActionListener(this);
    Return.setFont(new Font("Sans-serif", Font.BOLD, 18));
    Return.setBackground(Color.white);
    super.add(Return);

    HideHint.setFont(new Font("Sans-serif", Font.BOLD, 18));
    HideHint.setBackground(Color.white);

    super.add(HideHint);

    Return.setLocation(50, (frame.getHeight() - 75));
    Return.setSize(200, 30);

    HideHint.setLocation((frame.getWidth() / 2 - 150), (frame.getHeight() - 100));
    HideHint.setSize(300, 30);

    tm.start();
}

public void actionPerformed(ActionEvent e) {
    if(e.getSource() == Return){
        cl.show(MainPanel, "1");
        tm.stop();
        System.out.println("Rain Paused");
    }

    //First time rendering of the raindrops.
    Generate();

    for(int i = 0; i < amount; i++){
        y[i] += v[i];

        //Changing the velocity depending on location and gravity.
        Velocity(i);

        //Brightening the dropcolor the further down.
        ColorChange(i);

        //When a raindrop reaches the bottom of the screen
        Regenerate(i);

        Rain[i].setBackground(NewDropColor[i]);
        Rain[i].setLocation(x[i], y[i]);
    }
    flag = false;
}

public void Generate(){
    if(flag){
        for(int i = 0; i < amount; i++){
            Rain[i] = new JPanel();

            NewDropColor[i] = DropColor;
            Rain[i].setBackground(NewDropColor[i]);

            x[i] = (int) (Math.random() * frame.getWidth());       
            y[i] = (int) (Math.random() * -frame.getHeight());
            w[i] = (int) (Math.random() * 4);
            h[i] = (int) (Math.random() * 13);
            v[i] = (int) (Math.random() * 6);
            g[i] = (int) (Math.random() * 150);

            if(h[i] < 7) h[i] += 6;

            if(w[i] < 3) w[i] += 3;

            if(w[i] == 5) w[i] = 4;

            if(v[i] < 3) v[i] += 3;

            if(g[i] < 75) g[i] += 90;

            super.add(Rain[i]);
            Rain[i].setLocation(x[i], y[i]);
            Rain[i].setSize(w[i], h[i]);
        }
        System.out.println("Rain Running");
    }
}

public void ColorChange(int i){
    if(y[i] > -frame.getHeight()/10){
        if(y[i] % 10 == 0 || y[i] % 9 == 0){
            if(NewDropColor[i].getRed() < (256 - ColorIncrease) && NewDropColor[i].getGreen() < (256 - ColorIncrease) && NewDropColor[i].getBlue() < (256 - ColorIncrease)){
                NewDropColor[i] = new Color(NewDropColor[i].getRed() + ColorIncrease, NewDropColor[i].getGreen() + ColorIncrease, NewDropColor[i].getBlue() + ColorIncrease);
            }
        }
    }
}

public void Regenerate(int i){
    if(y[i] >= frame.getHeight()){
        x[i] = (int) (Math.random() * frame.getWidth()); 
        v[i] = (int) (Math.random() * 6);

        NewDropColor[i] = DropColor;

        if(v[i] < 3) v[i] += 3;

        y[i] = -10;
    }
}

public void Velocity(int i){
    if(y[i] % g[i] == 0 || y[i] % g[i] == 1 || y[i] % g[i] == 2){
        v[i] += 1;
    }
}

public static int SpeedRead(){
    int Speed = 0;
    try{
        String Ignore;
        BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream("Settings.txt")));
        Ignore = file.readLine();
        Ignore = file.readLine();

        Speed = Integer.parseInt(file.readLine());

        file.close();
    }
    catch(IOException e){
        System.out.println("Something went wrong loading Settings...");
    }

    return Speed;
}

public static Color DropColorRead(){
    Color DropColor = null;

    try{
        int Red, Green, Blue;
        String Color, Ignore;
        BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream("Settings.txt")));
        Ignore = file.readLine();
        Color = file.readLine();

        Red = Integer.parseInt(Color.substring(0, 3));
        Green = Integer.parseInt(Color.substring(4, 7));
        Blue = Integer.parseInt(Color.substring(8, 11));

        DropColor = new Color(Red, Green, Blue);
        file.close();
    }
    catch(IOException e){
        System.out.println("Something went wrong loading Settings...");
    }

    return DropColor;
}

public static Color BackgroundChange(){
    Color BackColor = null;

    try{
        int Red, Green, Blue;
        String Color;
        BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream("Settings.txt")));
        Color = file.readLine();

        Red = Integer.parseInt(Color.substring(0, 3));
        Green = Integer.parseInt(Color.substring(4, 7));
        Blue = Integer.parseInt(Color.substring(8, 11));

        BackColor = new Color(Red, Green, Blue);
        file.close();
    }
    catch(IOException e){
        System.out.println("Something went wrong loading Settings...");
    }

    return BackColor;
}

@Override
public void keyPressed(KeyEvent arg0) {
    System.out.println("asdhuasdiu");
}

@Override
public void keyReleased(KeyEvent arg0) {
    // TODO Auto-generated method stub
}

@Override
public void keyTyped(KeyEvent arg0) {
    // TODO Auto-generated method stub  
}
}    

There are a number of issues. 有很多问题。

First, you're adding the KeyListener to the JFrame , the problem with that is, a JFrame is made of a number of other components... 首先,您要将KeyListener添加到JFrame ,问题是JFrame由许多其他组件组成...

JRootPane

The next problem is, the KeyListener will only respond to key events if: 下一个问题是, KeyListener仅在以下情况下才响应按键事件:

  1. The component is focusable AND 该组件是可聚焦的
  2. The component has keyboard focus 该组件具有键盘焦点

So, when you add other components to the UI, I'm assuming that Return and HideHint are actually JButton s, they can, and often do, steal focus rendering your KeyListener useless. 因此,当您将其他组件添加到UI时,我假设ReturnHideHint实际上是JButton ,它们可以并且经常这样做,从而导致焦点窃取,从而使KeyListener无用。

As is almost the case with KeyListener , the answer is, don't use it. 就像KeyListener ,答案是不要使用它。 No seriously. 不认真 If you want more control over when a key event is triggered, then you should use the Key Bindings API which provides not only a more flexible and re-usable API, but provides you with control over how to configure the at what focus level a key event would be triggered 如果您想更好地控制按键事件的触发时间,则应该使用按键绑定API ,该API不仅提供更灵活,可重复使用的API,而且还可以控制如何在按键的焦点级别上进行配置事件将被触发

In order for the KeyListener to fire a KeyEvent, you have to be inside the Listened Object (it has to be in focus). 为了使KeyListener触发KeyEvent,您必须位于Listened Object内部(它必须处于焦点状态)。 If you put other Objects like Buttons or TextFields upon your Frame you block the keyListener on these places. 如果将诸如Button或TextFields之类的其他对象放置在Frame上,则会在这些位置阻止keyListener。

Try setting your KeyListener to super like so: 尝试将KeyListener设置为super如下所示:

super.addKeyListener(new KeyListener(){
    //code for listener
});

As stated in the comments, the problem you're having is that you're setting your KeyListener to a JFrame that is being passed into your constructor. 如评论中所述,您遇到的问题是将KeyListener设置为传递给构造函数的JFrame Then you are setting the object that is being constructed to be in focus by calling super.requestFocusInWindow() 然后,通过调用super.requestFocusInWindow()将正在构造的对象设置为焦点。

To allow the KeyListener to properly do it's job the Component to which the KeyListener is attached, must be in focus. 为了使KeyListener能够正常工作,必须将与KeyListener相连的Component放在焦点上。

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

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