gpt4 book ai didi

java - 使用按键绑定(bind)获取键码

转载 作者:行者123 更新时间:2023-12-02 00:35:19 24 4
gpt4 key购买 nike

我有一个显示缓冲图像的函数。我希望在加载图像的 JLabel 中实现鼠标监听器和按键监听器。由于 JLabel 无法获得焦点,我尝试使用 KeyBinding。但我注意到 KeyBinding 用于个人 key 。我想要的是每个按下的键的键码,无论按下哪个键。在这种情况下有办法获取 KeyCode 吗?我还注意到 KeyListener 和 MouseListener 在构造函数中工作,但在其他方法中不起作用。这是真的吗?

 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,但仍然无法获得键盘焦点。

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
}
});

关于java - 使用按键绑定(bind)获取键码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7976209/

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