为什么MousePressed永远不会被调用?

时间:2013-09-26 22:53:49

标签: java swing

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

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

   }
}

1 个答案:

答案 0 :(得分:3)

您既不会覆盖也不会在鼠标适配器中重载正确的方法。

MouseAdapter中不存在MousePressed,因此是一个永远不会被调用的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);
  }
});

OR

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