import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class USBMain {
public static void main(String[] args) {
USBMain u = new USBMain();
u.launchFrame();
// 开启盘符检查线程
new CheckRootThread().start();
}
// 界面
private void launchFrame() {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(450, 250);
JButton hide = new JButton("点击隐藏窗口");
// 点击按钮后隐藏窗口事件监听
hide.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
}
});
frame.add(hide);
frame.pack();
frame.setVisible(true);
frame.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
char charA = e.getKeyChar();
System.out.println("你按了《" + charA + "》键");
}
});
}
}
试了好几种方法,就是没有效果
Java中无法添加键盘监听
答案:1 悬赏:80 手机版
解决时间 2021-03-17 20:48
- 提问者网友:ミ烙印ゝ
- 2021-03-17 12:32
最佳答案
- 五星知识达人网友:逐風
- 2021-03-17 13:09
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.addKeyEventPostProcessor(new KeyEventPostProcessor() {
@Override
public boolean postProcessKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
System.out.println(e.getKeyChar());
}
return false;
}
});
manager.addKeyEventPostProcessor(new KeyEventPostProcessor() {
@Override
public boolean postProcessKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
System.out.println(e.getKeyChar());
}
return false;
}
});
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯