[英]How to add KeyListener to JComponent when mouse is entered?
I have created custom button class which extends JComponent
and want to add KeyListener
on mouseEntered
event (and later remove on mouseExited
). 我创建了自定义按钮类,它扩展了
JComponent
并希望在mouseEntered
事件上添加KeyListener
(稍后在mouseExited
删除)。 So my goal is - when the mouse enters this JComponent
- then if I press Enter - some code will be executed, related to only this button. 所以我的目标是 - 当鼠标进入这个
JComponent
- 如果我按下Enter键 - 将执行一些代码,仅与此按钮相关。 How can I do that? 我怎样才能做到这一点?
Use Key Bindings instead of KeyListeners, since the latter is way to low level for Swing
. 使用Key Bindings而不是KeyListeners,因为后者是
Swing
低级别。 Just bring your mouse over the JButton
, and then press ENTER , then take your mouse outside the bounds of the JButton
and try pressing ENTER again. 只要把鼠标移动到
JButton
,然后按ENTER键 ,然后把你的鼠标的边界之外JButton
,并尝试再次按ENTER键 。 Have a look at this example and see if this is what you wanted : 看一下这个例子,看看这是不是你想要的:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonBinding {
private JPanel contentPane;
private JTextField tField;
private JButton button;
private KeyStroke keyStroke = KeyStroke.getKeyStroke("ENTER");
private Action action = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Action Performed");
contentPane.setBackground(Color.BLUE);
}
};
private MouseAdapter mouseActions = new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent me) {
System.out.println("Mouse Entered");
JButton button = (JButton) me.getSource();
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "enter");
button.getActionMap().put("enter", action);
}
@Override
public void mouseExited(MouseEvent me) {
System.out.println("Mouse Exited");
JButton button = (JButton) me.getSource();
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "none");
contentPane.setBackground(Color.RED);
}
};
private void displayGUI() {
JFrame frame = new JFrame("Button Binding Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new JPanel();
contentPane.setOpaque(true);
tField = new JTextField(10);
button = new JButton("Click Me");
button.addMouseListener(mouseActions);
contentPane.add(tField);
contentPane.add(button);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
new ButtonBinding().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.