Jlabel在鼠标单击Java时更改颜色

时间:2018-08-08 05:45:30

标签: java swing jlabel

我正在使用for循环添加多个Jlabel。我想要的是单击鼠标,选定的JLabel的颜色应更改并设置为单击另一JLabel时的默认颜色。

enter code here

1 个答案:

答案 0 :(得分:3)

由于您更改了标签的状态,因此需要某种方式将其改回。最简单的解决方案是维护对上次更改的标签的引用,并在单击新标签后重置其状态

import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            HighlightMouseListener hml = new HighlightMouseListener();
            for (int index = 0; index < 10; index++) {
                JLabel label = new JLabel("Hello " + index);
                label.addMouseListener(hml);
                add(label, gbc);
            }
        }

    }

    public class HighlightMouseListener extends MouseAdapter {
        private JLabel previous;

        @Override
        public void mouseClicked(MouseEvent e) {
            Component source = e.getComponent();
            if (!(source instanceof JLabel)) {
                return;
            }
            JLabel label = (JLabel) source;
            if (previous != null) {
                previous.setBackground(null);
                previous.setForeground(null);
                previous.setOpaque(false);
            }
            previous = label;
            label.setForeground(Color.WHITE);
            label.setBackground(Color.BLUE);
            label.setOpaque(true);
        }

    }

}

我仍然想知道JList是否会是更好,更简单的解决方案,但是由于我不知道您在做什么,这就是我所能做的