Is there a way to set default cursor of JButton
components?
This is how to set cursor for a one JButton
:
JButton btn = new JButton("Click me");
btn.setCursor(new Cursor(Cursor.HAND_CURSOR));
According lookAndFeel Nimbus defaults there's no a property like "Button.cursor".
I'd like to set default cursor once so all the JButtons in the app have the same hand-cursor when the mouse cursor moves over.
You can have a custom button
that extends the JButton
and use that. Some thing like :
MyCustomJButton.java
import java.awt.Cursor;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
@SuppressWarnings("serial")
public class MyCustomJButton extends JButton implements MouseListener
{
private Cursor defaultCursor;
private Cursor handCursor;
public MyCustomJButton()
{
super();
init();
}
public MyCustomJButton(Action a)
{
super(a);
init();
}
public MyCustomJButton(Icon icon)
{
super(icon);
init();
}
public MyCustomJButton(String text, Icon icon)
{
super(text, icon);
init();
}
public MyCustomJButton(String text)
{
super(text);
init();
}
@Override
public void mouseClicked(MouseEvent e)
{
}
@Override
public void mousePressed(MouseEvent e)
{
}
@Override
public void mouseReleased(MouseEvent e)
{
}
@Override
public void mouseEntered(MouseEvent e)
{
this.setCursor(handCursor);
}
@Override
public void mouseExited(MouseEvent e)
{
this.setCursor(defaultCursor);
}
private void init()
{
defaultCursor = this.getCursor();
handCursor = new Cursor(Cursor.HAND_CURSOR);
addMouseListener(this);
}
}
Once you have implemented your own custom button, you can instantiate it like you would instantiate the JButton
.
MyCustomJButton myButton = new MyCustomJButton("My Button");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With