Changing value of boolean when mouse cursor hovers over a JButton

孤街浪徒 提交于 2019-12-04 05:33:56

问题


I have a button that will change from black to gray when you hover over, I do this with setRolloverIcon(ImageIcon);. Is there any easy way to make a boolean equals to true while the mouse cursor hovers over the JButton or would I have to use a MouseMotionListener to check the position of the mouse cursor?


回答1:


Is there any easy way to make a boolean equals to true while the mouse cursor hovers over the JButton

you can to add ChangeListener to ButtonModel, e.g.

JButton.getModel().addChangeListener(new ChangeListener() {
    @Override
    public void stateChanged(ChangeEvent e) {
        ButtonModel model = (ButtonModel) e.getSource();
        if (model.isRollover()) {
            //do something with Boolean variable
        } else {

        }
    }
});



回答2:


This is an example of using the ButtonModel:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class TestButtons {

    protected void createAndShowGUI() {
        JFrame frame = new JFrame("Test button");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JButton button = new JButton("Hello");
        button.getModel().addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                if (button.getModel().isRollover()) {
                    button.setText("World");
                } else {
                    button.setText("Hello");
                }
            }
        });
        frame.add(button);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestButtons().createAndShowGUI();
            }
        });
    }

}



回答3:


Try this:

button.addMouseListener(new MouseListener() {

    public void mouseEntered(MouseEvent e) {
        yourBoolean = true;
    }
}

good luck



来源:https://stackoverflow.com/questions/16733708/changing-value-of-boolean-when-mouse-cursor-hovers-over-a-jbutton

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