简体   繁体   中英

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");
   }
}                                           

Updating the UI component alone is often not enough; you also have to trigger a repaint action.

In other words: there are two "layers" here. One is the "data model" (where some button knows about its text); the other is the actual "graphical content". The later one comes into existence by somehow displaying the first parts. Therefore both layers need to be addressed in order to make your chances visible to the user.

See here for some examples around that.

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");
        }
    });
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM