一个MouseListener,用于许多JLabel组件

时间:2016-02-17 05:26:43

标签: java swing event-handling mouselistener mouse-listeners

我有17个https://wordpress.org/plugins/php-code-for-posts/ 组件,我想为所有这些标签添加相同的处理程序。实际上,当鼠标悬停在标签上时,我必须增加标签的大小。代码在这里:

JLabel

现在我想避免重复相同的处理程序。

1 个答案:

答案 0 :(得分:4)

这很简单 - 您可以使用相同的鼠标处理程序类,并可以将其分配给多个JLabel,然后通过MouseEvent#getSource()方法获取当前涉及的JLabel。

@Override
public void mouseEntered(MouseEvent evt) {
    // assuming that you only add this MouseListener to JLabels...
    JLabel currentLabel = (JLabel)evt.getSource();

    // do what needs to be done with currentLabel

}

例如:

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;

@SuppressWarnings("serial")
public class ManyLabelExample extends JPanel {
    private static final int SIDES = 8;
    private static final int GAP = 15;
    public static final Color HOVER_COLOR = Color.pink;
    private List<JLabel> labels = new ArrayList<>();

    public ManyLabelExample() {
        setLayout(new GridLayout(SIDES, SIDES));
        MyMouseHandler myMouseHandler = new MyMouseHandler();
        for (int i = 0; i < SIDES * SIDES; i++) {
            String text = String.format("[%d, %d]", i % SIDES + 1, i / SIDES + 1);
            JLabel label = new JLabel(text);
            label.setOpaque(true);
            label.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
            label.addMouseListener(myMouseHandler);
            labels.add(label);
            add(label);
        }
    }

    private class MyMouseHandler extends MouseAdapter {
        @Override
        public void mouseEntered(MouseEvent evt) {
            JLabel source = (JLabel) evt.getSource();
            for (JLabel label : labels) {
                if (label == source) {
                    label.setBackground(HOVER_COLOR);
                } else {
                    label.setBackground(null);
                }
            }
        }

    }

    private static void createAndShowGui() {
        ManyLabelExample mainPanel = new ManyLabelExample();

        JFrame frame = new JFrame("ManyLabelExample");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}