1

我创建了自定义按钮类,它扩展JComponent并希望添加KeyListeneronmouseEntered事件(然后删除 on mouseExited)。所以我的目标是 - 当鼠标进入这个JComponent- 然后如果我按下 Enter - 一些代码将被执行,仅与这个按钮相关。我怎样才能做到这一点?

4

1 回答 1

4

使用Key Bindings而不是 KeyListeners,因为后者对于Swing. 只需将鼠标移到 上JButton,然后按ENTER,然后将鼠标移到 边界外,然后再次JButton尝试按ENTER。看看这个例子,看看这是否是你想要的:

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);
    }
}
于 2013-08-14T14:56:14.193 回答