简体   繁体   中英

mouseEntered is not working

I have an array of 5 JLabel objects and I have added mouse listener to all of them, in mouseEntered() function I am making the label opaque(true) to change its background color, but this code is not working properly, please help.

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class A extends MouseAdapter {
    JFrame frame = new JFrame();
    JLabel label[] = new JLabel[5];

    A() {
        frame.setSize(500,500);
        frame.setLayout(new FlowLayout());
        for(int i=0; i<5; i++) {
            label[i] = new JLabel("LABEL: "+i);
            label[i].setBackground(Color.BLACK);
            label[i].addMouseListener(this);
            frame.add(label[i]);
        }
        frame.setVisible(true);
    }

    public static void main(String arg[]) {
                new A();
    }

    @Override
    public void mouseEntered(MouseEvent entered) {
        if(entered.getSource().equals(label))
            ((JLabel)entered.getComponent()).setOpaque(true);
    }
}

The likely cause is if(entered.getSource().equals(label))

The source of the event will never be the label array, but will be one of it's elements. A better condition might be if(entered.getSource() instanceof JLabel)

And you'll also need entered.getComponent().repaint(); after you change the opacity property of the label

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