简体   繁体   中英

MouseListener doesn't appear to be working for me

I need to preface this with my instructor doesn't let us use IDE's. We use TextPad. I want to click on this label and it then change from "H" to "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. 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 . The fact that the JLabel is its own listener doesn't absolve you of this responsibility.

You never added the MouseListener to your label.

To do this, simply add the following code:

    addMouseListener(this);

That's because you need to add the mouse listener to your JLabel. In your constructor add:

addMouseListener(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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