1

在下面的代码中,单击标签应该使其隐藏,但该方法永远不会被调用!我在这里想念什么?

    package com.hermaryopto.lib.output.message;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class CDisplayMessage  {
   JLabel label;
   public CDisplayMessage(Container  parent, int top, int left, int width, int height, int fontSize){
      label = new JLabel ();
      label.setFont(new Font("Arial", Font.PLAIN, fontSize));
      label.setOpaque(true);
      label.setBackground(Color.ORANGE);
      label.setCursor(new Cursor(Cursor.HAND_CURSOR));
      label.setBounds(top, left, width, height);
      int w = width;
      int h = height;
      label.setMinimumSize(new Dimension(w,h));
      label.setPreferredSize(new Dimension(w,h));
      label.setMaximumSize(new Dimension(w,h));

      parent.add(label);
//--------- This mouse pressed never gets called why?
      label.addMouseListener(new MouseAdapter(){
         public void MousePressed(MouseEvent e){
            label.setVisible(false);    
         }
      });

   }

   public void message(String sMessage, final Color color){
     label.setText(sMessage);
   }

  public void repaint(){
      label.repaint();
   }

   public static void main( String [] args){
      JFrame frame = new JFrame();
      CDisplayMessage cp = new CDisplayMessage(frame, 10,10, 100,100,22);
      cp.message("click here to hide this text", Color.red);
      frame.setVisible(true);
      frame.setSize(new Dimension(200,200));

   }
}
4

1 回答 1

3

您既没有覆盖也没有重载鼠标适配器中的正确方法。

MousePressed 在 MouseAdapter 中不存在,因此是永远不会调用的 MouseAdapter 实现的自定义方法。mousePressed 是您希望调用的方法。在 Eclipse IDE 中,您可以使用帮助程序(我认为是 ctrl+space)来查看您可以为匿名类覆盖的所有方法。

代替:

label.addMouseListener(new MouseAdapter() {
  public void MousePressed(MouseEvent e) {
    label.setVisible(false);
  }
});

为了

label.addMouseListener(new MouseAdapter() {
  @Override
  public void mousePressed(MouseEvent e) {
    label.setVisible(false);
  };
});

............

更新:

现在,如果你真的,真的想打电话给 MousePressed(因为这是你的问题,我真傻!)

你可以这样使用它:

// --------- This mouse pressed never gets called why?
label.addMouseListener(new MouseAdapter() {
  @Override
  public void mousePressed(MouseEvent e) {
    MousePressed(e)
  };

  public void MousePressed(MouseEvent e) {
    label.setVisible(false);
  }
});

或者

MouseAdapter myMouseAdapter = new MouseAdapter() {
      public void MousePressed(MouseEvent e) {
        label.setVisible(false);
      }
    };
label.addMouseListener(myMouseAdapter);
myMouseAdapter.MousePressed(mouseEventInstance);
于 2013-09-26T22:55:33.043 回答