问题
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