简体   繁体   English

MouseListener似乎不适合我

[英]MouseListener doesn't appear to be working for me

I need to preface this with my instructor doesn't let us use IDE's. 我需要在我的讲师的前言下,不要让我们使用IDE。 We use TextPad. 我们使用TextPad。 I want to click on this label and it then change from "H" to "T". 我想点击这个标签,然后从“H”变为“T”。 Currently when I click the label does nothing. 目前,当我点击标签什么也没做。 What am I forgetting? 我忘记了什么?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class Lab3Label extends JLabel implements MouseListener {
    int count = 0;
    boolean flag = true;

    public Lab3Label (int i) {
        setLayout(new BorderLayout());
        count = i;
        this.setText("H");
        this.setFont(new Font("Serif", Font.PLAIN, 60));
        this.setBorder(BorderFactory.createLineBorder(Color.black));
    }

    public void mouseReleased(MouseEvent e)
        {

            if(flag){
                this.setText("H");
                flag = false;
            }

            else{
                this.setText("T");
                flag = true;
            }
        }

    public void mouseExited(MouseEvent e){}
    public void mouseClicked(MouseEvent e){}
    public void mousePressed(MouseEvent e){}
    public void mouseMoved(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}


}

Your JLabel implements MouseListener , but you also need to tell the JLabel to send events to itself. 您的JLabel实现了MouseListener ,但您还需要告诉JLabel将事件发送给自己。 At the end of the constructor you'll need to say 在构造函数的最后你需要说

addMouseListener(this);

This makes more sense if you remember that you can make any class into a MouseListener , and you'd have to connect your listener to your JLabel . 如果你记得你可以将任何类放入MouseListener ,并且你必须将你的监听器连接到你的JLabel ,这就更有意义了。 The fact that the JLabel is its own listener doesn't absolve you of this responsibility. JLabel是其自己的倾听者这一事实并不能免除您的责任。

You never added the MouseListener to your label. 您从未将MouseListener添加到标签中。

To do this, simply add the following code: 为此,只需添加以下代码:

    addMouseListener(this);

That's because you need to add the mouse listener to your JLabel. 那是因为你需要将鼠标监听器添加到你的JLabel。 In your constructor add: 在你的构造函数中添加:

addMouseListener(this);

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

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