How to add KeyListener to JComponent when mouse is entered?

二次信任 提交于 2019-12-11 08:24:54

问题


I have created custom button class which extends JComponent and want to add KeyListener on mouseEntered event (and later remove on 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. How can I do that?


回答1:


Use Key Bindings instead of KeyListeners, since the latter is way to low level for 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. 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);
    }
}


来源:https://stackoverflow.com/questions/18234500/how-to-add-keylistener-to-jcomponent-when-mouse-is-entered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!