Java中无法添加键盘监听
importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.e...
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 + "》键");
}
});
}
}
试了好几种方法,就是没有效果 展开
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 + "》键");
}
});
}
}
试了好几种方法,就是没有效果 展开
展开全部
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;
}
});
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询