gpt4 book ai didi

java - 按键监听器不工作

转载 作者:行者123 更新时间:2023-12-02 07:02:59 25 4
gpt4 key购买 nike

public class KL implements KeyListener {

public static void main(String[] args) {
final JPopupMenu popup = new JPopupMenu();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);

}

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

@Override
public void keyReleased(KeyEvent e) {
System.out.println(e.getKeyChar());

}

@Override
public void keyTyped(KeyEvent e) {
System.out.println(e.getKeyChar());

}
}

那是我的类(class),对我来说这可能是非常愚蠢的事情,但是我的 KeyListener 不起作用。控制台上没有任何显示。

最佳答案

让我们从您没有将监听器附加到任何东西的事实开始,然后继续讨论您确实应该使用 Key Bindings 的事实

举例

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestTableEditing {

public static void main(String[] args) {
new TestTableEditing();
}

public TestTableEditing() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

private JLabel key;
private int counter = 0;

public TestPane() {
key = new JLabel("...");
add(key);
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "A.pressed");
am.put("A.pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("A was pressed");
key.setText("A was pressed " + (++counter));
}
});
}

}

}

关于java - 按键监听器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16409352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com