繁体   English   中英

使用instanceof更改JLabels的颜色

[英]Using instanceof to change color of JLabels

我正在寻找通过函数来​​更改所有JLabel的文本颜色的方法,因此我不必对每个参数都使用setForegroundColor

目前,在名为Main的面板中有一堆JLabel 我做了一些研究,发现了instanceofgetComponents方法。 所以我走了这么远:

main = new JPanel();
    main.setBackground(Color.red);
    tf_search = createTF();
    l_name1 = new JLabel("Name: "+ DB.findUser(1001).returnName());
    l_nick = new JLabel("Nick: " + DB.findUser(1001).returnNick());
    l_style = new JLabel("Style: ");
    l_styleshow = new JLabel(DB.findUser(1001).returnStyle());
    l_music = new JLabel("Favourite songs: ");
    l_musicshow1 = new JLabel(DB.findUser(1001).returnMusic1());
    l_musicshow2 = new JLabel(DB.findUser(1001).returnMusic2());
    l_musicshow3 = new JLabel(DB.findUser(1001).returnMusic3());
    l_blank = new JLabel("");
    l_blank2 = new JLabel("");
    l_inst = new JLabel("Instrument: ");
    l_instshow = new JLabel(DB.findUser(1001).returnInst());
    l_band = new JLabel("Band: ");
    l_bandshow = new JLabel(DB.findUser(1001).returnBand());
    b_search  = new JButton("Sök");
    b_musicchn = new JButton("Edit Profile");
    b_return = new JButton("Return to profile");


    main.setLayout(new GridLayout(9,2));
    main.add(l_name1);
    main.add(l_nick);
    main.add(l_style);
    main.add(l_styleshow);
    main.add(l_music);
    main.add(l_musicshow1);
    main.add(l_blank);
    main.add(l_musicshow2);
    main.add(l_blank2);
    main.add(l_musicshow3);
    main.add(l_band);
    main.add(l_bandshow);
    main.add(l_inst);
    main.add(l_instshow);
    main.add(b_search);
    b_search.addActionListener(new searchHandler());
    main.add(b_musicchn);
    b_musicchn.addActionListener(new editHandler());
    main.add(tf_search);
    main.add(b_return);
    b_return.addActionListener(new returnHandler());

所有的面板和东西都被声明,或称其为什么。 前“私人JLabel l_nick等”

因此,我认为这可能会选择所有JLabels并将文本更改为白色,但是我的代码无法正常运行。 这是一种合法的做事方式,您可以纠正吗,还是有人知道另一种方式。 提前致谢!

注意:我是一名学生,这是我在第一个编程年的最后一个项目,所以我只想代码多样化。 如果无法通过海量的高级代码块进行操作,即使感谢您的帮助,也不要打扰您输入它!

不要这样做:

main.getComponents(l_label instanceof JLabel).setForegroundColor(Color.White);

而是定义一个List<JLabel> mylabels = ...填充列表:

myLabels.add(l_label);
myLabels.add(l_label2);
myLabels.add(l_label3);

并做一个增强

for(JLabel x:myLabels){

    x.setForegroundColor(Color.White);

}

您可以检索所有子组件,检查它们是否为JLabel ,并相应地设置颜色。

    for (Component component : panel.getComponents()) {

        if (component instanceof JLabel) {

            component.setForeground(Color.WHITE);
        }

    }

我不知道带有过滤器参数的方法getComponents 但是您可以使用流进行过滤。 像这样:

Stream.of(main.getComponents()).filter(component -> component instanceOf JLabel).forEach(label -> ((JLabel)label).setForegroundColor(Color.White));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM