简体   繁体   English

添加计时器时,JPanel不响应KeyListener吗?

[英]JPanel doesn't response to KeyListener when i add a timer?

I don't Understand why JPanel doesn't response to KeyListener when i add the following : 我不明白为什么当我添加以下内容时,JPanel不响应KeyListener:

timer = new Timer(80,this);
timer.start();

and it works when i comment it ?? 它在我评论时有效吗??

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class Test extends JPanel implements KeyListener,ActionListener{

    private static final long serialVersionUID = 1L;
    private Timer timer ;
    public Test( )  {
        addKeyListener(this);
        setFocusable(true);
        setBackground(Color.RED);
        setFocusTraversalKeysEnabled(false);
        setPreferredSize(new Dimension(700, 700));
        //timer = new Timer(80,this);
        //timer.start();
    }
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        Test t = new Test();
        frame.add(t);
        frame.pack();

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

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

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

    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //timer.start();

    }
}

Nothing happens because KeyEvents are only generated for the component with focus. 什么也没发生,因为KeyEvent仅针对具有焦点的组件生成。 Your panel doesn't have focus. 您的面板没有焦点。

The order of the code should be: 代码的顺序应为:

    Test t = new Test();
    frame.add(t);
    frame.pack();
    frame.setVisible(true);

That is you need to add the components to the frame before the frame is visible, then focus will be placed on the panel. 那就是您需要在框架可见之前将组件添加到框架,然后将焦点放在面板上。

However, that is still not the proper solution because the panel could lose focus in which case your code will stop working. 但是,这仍然不是正确的解决方案,因为面板可能会失去焦点,在这种情况下您的代码将停止工作。

The better solution when using Swing is to use Key Bindings . 使用Swing时更好的解决方案是使用Key Bindings Key Bindings allow you to bind a KeyStroke to an Action even when the component doesn't have focus. 按键绑定使您即使在组件没有焦点的情况下也可以将KeyStroke绑定到Action 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