简体   繁体   English

你如何使用keylistener?

[英]How do you use a keylistener?

It seems I can't make my program to notice the fact that I'm pressing a button.似乎我无法让我的程序注意到我正在按下按钮的事实。 I've seen at a lot of tutorials and images and I think this code should work but it just won't.我看过很多教程和图片,我认为这段代码应该可以工作,但它不会。 Can anybody help me?有谁能够帮我?

 package projekt;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

public class Projekt extends javax.swing.JFrame implements KeyListener {


public Projekt() {
    initComponents();
    this.addKeyListener(this);
}

 [...]

@SuppressWarnings("unchecked")

@Override
public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_A){
        System.out.println("It works!!!"); //It won't print this
}


@Override
public void keyTyped(KeyEvent e) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

@Override
public void keyReleased(KeyEvent e) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}

A KeyEvent is only dispatch to the component that has focus. KeyEvent 仅调度到具有焦点的组件。

this.addKeyListener(this);

You are adding the KeyListener to the frame.您正在将 KeyListener 添加到框架中。 The frame does not have focus.框架没有焦点。 A component displayed on the frame has focus.显示在框架上的组件具有焦点。

I can't seem to get my program to pick up the fact that I'm pressing a button.我似乎无法让我的程序了解我正在按下按钮的事实。

You should not be using a KeyListener to listen for specific key events.您不应该使用 KeyListener 来监听特定的键事件。 That is old AWT code.那是旧的 AWT 代码。

In Swing you should be using Key Bindings .在 Swing 你应该使用Key Bindings Key Bindings will allow you to listen for a KeyStroke even if the component doesn't have focus.即使组件没有焦点, Key Bindings也允许您侦听 KeyStroke。

Read the section from the Swing tutorial on How to Use Key Bindings for more information.阅读 Swing 教程中有关如何使用键绑定的部分以获取更多信息。

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

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