Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JButton default cursor

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.

like image 439
Martin Ille Avatar asked Nov 09 '22 22:11

Martin Ille


1 Answers

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");
like image 122
always_a_rookie Avatar answered Nov 14 '22 21:11

always_a_rookie