简体   繁体   English

进入鼠标,退出鼠标,更改每个事件按钮上的文本

[英]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. 我试图连接一个按钮,当鼠标进入它时说“ Hi”,而当鼠标离开时说“ Bye”。 I have been using mouse events with a MouseListener but to no avail. 我一直在使用MouseListener的鼠标事件,但无济于事。

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. 我是Java的新手,在过去的两天里,这个问题一直困扰着我,而我一直无法弄清楚。 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; 仅更新UI组件通常是不够的。 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");
        }
    });
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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