Changing boolean value when mouseover over JButton

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

+1
source share
3 answers

Is there an easy way to make a boolean value true while the mouse is over the JButton

you can add ChangeListener to ButtonModel for example.

 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 { } } }); 
+6
source

This is an example of using 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
source

Try the following:

 button.addMouseListener(new MouseListener() { public void mouseEntered(MouseEvent e) { yourBoolean = true; } } 

luck

+2
source

All Articles