【问题标题】:java eclipse windowbuilder keyPressed event does not firejava eclipse windowbuilder keyPressed事件不会触发
【发布时间】:2017-09-10 16:54:36
【问题描述】:

我的程序有一个我无法解决的问题。我尝试了几个小时并尝试使用谷歌等...我已经看到了许多正在运行的程序,但我不知道为什么我的解决方案不起作用。我的目标(现在)很简单,我想在鼠标单击或按键的情况下写入 cmd 行。第一个有效,但第二个无效。谁能告诉我为什么?

import java.awt.EventQueue;

import javax.swing.JFrame;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class test {

    private JFrame frame;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    test window = new test();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public test() {
        initialize();
    }

    private void initialize() {
        frame = new JFrame();
        frame.getContentPane().addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                System.out.println("Mouse has clicked!");
            }
        });
        frame.getContentPane().addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent arg0) {
                System.out.println("A key has pressed.");
            }
        });
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

【问题讨论】:

  • 1) 对于 Swing,我们通常使用 key bindings 而不是较低级别的 KeyListener。 2) “我尝试了几个小时并尝试使用谷歌等...我看到了很多程序,它们都在工作,但我不知道为什么我的解决方案不起作用。” 我'我很难理解为什么在你尝试的'许多程序'中,你没有看到有问题的组件需要既可聚焦又要有输入焦点才能使关键侦听器工作。 (或者说这是键绑定帮助我们解决的问题之一!)
  • 你试过frame.add...Listener(...)而不是frame.getContentPane().add...Listener(...)吗?

标签: java eclipse swing keypress windowbuilder


【解决方案1】:

好吧,我终于有足够的时间尝试找到解决方案,现在我发现了它。我不知道为什么,但无法将 keyListener 添加到 JFrame。我只能为 JButton 或 JTextField 等添加...这对我来说有点奇怪:c

【讨论】:

  • "我不知道为什么,但是无法将 keyListener 添加到 JFrame。我只能为 JButton 或 JTextField 等添加...这对于我,一点点” 如果您阅读并理解了我 2 天前的评论,则不应该如此。
猜你喜欢
  • 1970-01-01
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-09
  • 1970-01-01
  • 2012-05-02
  • 1970-01-01
相关资源
最近更新 更多