日期:2014-05-20  浏览次数:20646 次

怎么一次设置所有JLabel前景色
 在一个JPanel addN个JLabel。请问有什么方法 一次设置所有JLabel的前景色么?是不用数组。                                                                                             help :)
------最佳解决方案--------------------
可以使用UIManager来设置
import java.awt.BorderLayout;
import java.awt.Color;

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

public class Test {

    public static void main(String[] args) {
        UIManager.put("Label.foreground", Color.BLUE);
        JFrame frame = new JFrame("Label");
        JLabel label1 = new JLabel("Label One");
        JLabel label2 = new JLabel("Label Two");

        frame.getContentPane().add(label1);
        frame.getContentPane().add(label2, BorderLayout.SOUTH);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

------其他解决方案--------------------
楼上正解!

UIManager.put("Label.foreground", Color.BLUE);设置必须在系统界面初始化之前

但是通过UIManager来设置,会影响到系统中所有的Label控件,影响其他模块、子系统的显示。

另一种是自己封装Label,在自己的系统中new 封装后的Label子类。
------其他解决方案--------------------
private JLabel makeLabel(String text){
    JLabel label = new JLabel(text);
    label.setForeground(Color.BLUE);
    return label;
}

JPanel panel = ...;
panel.add(makeLabel("Hello"));
panel.add(makeLabel("Goodbye"));

------其他解决方案--------------------
该回复于2011-01-17 13:44:37被版主删除
------其他解决方案--------------------
谢谢各位大牛~!
------其他解决方案--------------------
我来总结一下:
天意如刀:统一设置成一种颜色,以一代万
Arthur(亚瑟王)和 逸飞的更灵活,可以分别设置
小弟学习了!
------其他解决方案--------------------
label.setForeground(Color.BLUE);
应该是setBackground 吧?