如何在Java中更改标签颜色?

SL_*_*ser 2 java concurrency swing jlabel

我在LinkList调用"l"中设置了标签,我需要更改这些标签的背景颜色.我需要在每次换色之间留出2秒的间隙,所以我尝试使用重绘方法如下,但它没有给我所需的结果.有人可以帮我解决这个问题吗?

    public static void changeColor(LinkedList l,JFrame f){

    for (int i = 0; i < l.size(); i++) {
        try {
            final JLabel xx = (JLabel) l.get(i);
            xx.setBackground(Color.red);
            f.repaint();
            xx.setText("B");
            System.out.println(i);
            new thread().run();
            xx.setBackground(Color.GRAY);
            xx.setText("A");
            f.repaint();

            } catch (Exception ex) {
               Logger.getLogger(TestView.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

mKo*_*bel 5

JLabel是defalut non-Opaque,即使你setBackGround(无论如何),然后没有定义myLabel.setOpaque(true);没有JLabel'area着色,另一种方式是使用CustomPaint与overover paintComponetn(),例如

在此输入图像描述

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

public class LabelBackGround {

    private JFrame frame;

    public LabelBackGround() {
        JLabel lblWest = new JLabel();
        lblWest.setPreferredSize(new Dimension(50, 150));
        lblWest.setOpaque(true);
        lblWest.setBackground(Color.red);
        JLabel lblEast = new JLabel();
        lblEast.setPreferredSize(new Dimension(50, 150));
        lblEast.setOpaque(true);
        lblEast.setBackground(Color.red);
        frame = new JFrame();
        frame.add(new CustomColoredComponents(), BorderLayout.NORTH);
        frame.add(new CustomColoredComponents(), BorderLayout.SOUTH);
        frame.add(lblWest, BorderLayout.WEST);
        frame.add(lblEast, BorderLayout.EAST);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation(100, 100);
        frame.pack();
        frame.setVisible(true);
    }

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

            @Override
            public void run() {
                LabelBackGround gridBadFrame = new LabelBackGround();
            }
        });
    }
}

class CustomColoredComponents extends JLabel {

    private static final long serialVersionUID = 1L;

    @Override
    public Dimension getMinimumSize() {
        return new Dimension(200, 20);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(200, 30);
    }

    @Override
    public void paintComponent(Graphics g) {
        int margin = 10;
        Dimension dim = getSize();
        super.paintComponent(g);
        g.setColor(Color.blue);
        g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

并且,您张贴空间具有了太多的问题,并发性的摇摆,然后从所有输出BackGroung Tasks到GUI必须被包裹成invokeLater()和你的代码块最后行代码会revalidate ()repaint()用于填充JComponents可见集装箱内