Question

Since my previous post was a mess, I decided to repost it but hopefully much cleaner this time.

So here is the code I'm trying to work with:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class sample extends JFrame implements ActionListener, MouseListener
{
        JButton b1, b2;
        JPanel panel1;
        JDialog dialog;


public sample()
{
    dialog = new JDialog();
    dialog.setBounds (0,0,200,200);

    panel1 = new JPanel();
    panel1.setLayout (new FlowLayout());

    b1 = new JButton("B1");
    add(b1);
    b1.addActionListener (this);
    b1.addMouseListener (this);

    b2 = new JButton ("B2");
    panel1.add(b2);
    b2.addMouseListener (this);
    dialog.add(panel1);

             /* I tried this but it didn't work as well:
             dialog.addMouseListener(this);
             panel1.addMouseListener(this); */
    }

    public void actionPerformed (ActionEvent e)
    {
    if (e.getSource () == b1)
        {
            dialog.setVisible (true);
        }
    }

    public void mouseClicked (MouseEvent e)
    {

    }
    public void mouseEntered (MouseEvent e)
    {
        setCursor (new Cursor (Cursor.HAND_CURSOR));
    }
    public void mouseExited (MouseEvent e)
    {
        setCursor (new Cursor(Cursor.DEFAULT_CURSOR));
    }
   public void mousePressed (MouseEvent e)
    {
    }
    public void mouseReleased (MouseEvent e)
    {
    }

    public static void main (String[] args) {
    sample s = new sample();
    s.setVisible (true);
    s.setBounds (0,0,200,200);
}
}

My goal is for the cursor to change to the hand cursor when the user hovers over B2, but it doesn't. What am I missing?

Was it helpful?

Solution

Your problem in next:

You set Cursor to sample instance(JFrame), not to JButton, for setting cursor on button change setCursor (new Cursor (Cursor.HAND_CURSOR)); to ((JComponent)e.getSource()).setCursor (new Cursor (Cursor.HAND_CURSOR));

Also for that purposes you needn't to use MouseListener you can just use:

b1.setCursor(new Cursor (Cursor.HAND_CURSOR));

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top