简体   繁体   English

如何将mouseListener添加到匿名JLabel对象?

[英]How do i add a mouseListener to a anonymous JLabel object?

Currently I'm using a for-loop to populate the JPanel with numbers from 1-31 目前,我正在使用for循环,以1-31中的数字填充JPanel

So basically, What I want to do is if let say i click on number 1, it will do show 所以基本上,我想做的是,如果说我单击数字1,它将显示

System.out.println(1);

Here's the code: 这是代码:

     public class MonthPanel extends JPanel implements MouseListener {

        public MonthPanel() {
            setLayout(new GridLayout(6,7));
            // Add headers
                // Use for-each loop.
                for (String header : headers) {
                  add(new JLabel(header));
                }

                for (int i = 1; i < 31; i++) {
                  add(new JLabel(String.valueOf(i)));
                }

            addMouseListener(this);
        }

    public void mouseClicked(MouseEvent e) {
            // What should i do in here to get a specific JLabel? 
               }
        }
}

Here's the picture 这是图片

在此处输入图片说明

Here's the solution 这是解决方案

First you have to add mouselistener in label which should have mouse adapter in brackets its because you only want to use mouse click method. 首先,您必须在标签中添加mouselistener,该标签的括号中应包含鼠标适配器,因为您只想使用鼠标单击方法。

Than add mouseClicked method in it . 比在其中添加mouseClicked方法。

and than add you code in mouseClicked method. 而不是在mouseClicked方法中添加代码。

Example: 例:

    JLabel l = new JLabel("label");
    l.addMouseListener(new MouseAdapter() {

        public void mouseClicked(MouseEvent e) {

            // Your Code Here

        }

    });
    add(l);

Instead of adding like that you can do something like 不必像这样添加,您可以做类似的事情

for (String header : headers) {
      JLabel lbl = new JLabel(header);
      lbl.addMouseListener(add ur listner);
      add(lbl);
}

In the mouseClicked event you can get the JLabel and print its text as follows 在mouseClicked事件中,您可以获取JLabel并按如下所示打印其文本

public void mouseClicked(MouseEvent e) {
    System.out.println(((JLabel) e.getSource()).getText());
}

In your code if you implement the MouseListener interface you must override all the abstract method in that. 在代码中,如果实现MouseListener接口,则必须重写其中的所有抽象方法。 Otherwise it will not compile 否则它将无法编译

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

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