Search code examples
javamouseeventmouselisteneronmouseover

Mouse entered, mouse exited changing the text on the button on each event


I am trying to connect a button to say "Hi" when the mouse enters it and "Bye" when the mouse leaves. I have been using mouse events with a MouseListener but to no avail.

I'm new to Java and this question has been plaguing me for the last 2 days and I just have not been able to figure it out. Any help would be greatly appreciated.

private abstract class HandlerClass implements MouseListener {
}

private abstract class Handlerclass implements MouseListener {
   @Override
   public void mouseEntered(java.awt.event.MouseEvent e) {
      mousebutton.setText("Hi");
   }

   @Override
    public void mouseExited(java.awt.event.MouseEvent e) {
      mousebutton.setText("Bye");
   }
}                                           

Solution

  • Try like this. It is working for me.

    public class ChangeTextMouseEvent extends Frame
    {
    static JButton btn;
    public ChangeTextMouseEvent()
    {
        setTitle("ChangeText");
        btn = new JButton("SSS");
        add(btn);
        setVisible(true);
        setBounds(0, 0, 100, 100);
    }
    public static void main(String[] args)
    {
        ChangeTextMouseEvent frame = new ChangeTextMouseEvent();
        btn.addMouseListener(new MouseAdapter(){
            @Override
            public void mouseExited(MouseEvent e)
            {
                btn.setText("Bye");
            }
            @Override
            public void mouseEntered(MouseEvent e)
            {
                btn.setText("Hi");
            }
        });
    }
    }