我有一个显示缓冲图像的功能。我希望在加载图像的JLabel中实现鼠标侦听器和键侦听器。由于JLabel无法获得焦点,因此我尝试使用KeyBinding。但是我注意到KeyBinding用于个人密钥。我想要的是与每个按键无关的每个按键的键控代码。在这种情况下有没有办法获取KeyCode?我也注意到KeyListener和MouseListener可在Constructor中工作,但不能在其他方法中工作。是真的吗
public void imageloader(BufferedImage image) throws InterruptedException {
// frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension dimension = new Dimension(image.getWidth(), image.getHeight());
setSize(200, 100);
setVisible(true);
label.removeAll(); //label is Jlabel
label.setIcon(new ImageIcon(image));
frame.setSize(dimension);
label.revalidate();
JScrollPane pane = new JScrollPane(label,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(pane);
frame.setSize(dimension);
// frame.setVisible(true);
}
更新:
我更改了方法,尽管MouseEvents被触发了,但仍然无法获得KeyBoard Focus。
public void imageloader(BufferedImage image) throws InterruptedException {
final String eol = System.getProperty("line.separator");
final JTextArea ta = new JTextArea(15, 60);
ta.setEditable(false);
Dimension dimension = new Dimension(Bimage.getWidth(), Bimage.getHeight());
gui.add(new JScrollPane(ta), BorderLayout.CENTER);
gui.add(l, BorderLayout.NORTH);
gui.setSize(dimension);
l.setFocusable(true);
//l.setOpaque(true);
l.removeAll();
l.setIcon(new ImageIcon(Bimage));
l.revalidate();
l.addFocusListener(new FocusListener() {
Color focused = Color.CYAN;
Color unfocused = Color.ORANGE;
public void focusLost(FocusEvent fe) {
System.out.println("Unfocused");
}
public void focusGained(FocusEvent fe) {
System.out.println("Focused");
}
});
l.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent me) {
System.out.println("Mouse Entered");
}
@Override
public void mouseExited(MouseEvent me) {
System.out.println("Mouse Exited");
}
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse Clicked");
}
});
l.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent ke) {
System.out.println("Key Typed");
}
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed");
}
});
frame.getContentPane().add(gui);
frame.setSize(dimension);
}
最佳答案
I don't know from where you knew JLabel can get Focus.
Documentation here clearly explains it cannot get Keyboard Focus.
让我们回到KeyBindings
myLabel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke((KeyEvent.DEL), 0, false), "DELETE");
myLabel.getActionMap().put("DELETE", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
// any/some Action
}
});