gpt4 book ai didi

java - 使用instanceof改变JLabels的颜色

转载 作者:行者123 更新时间:2023-11-30 02:35:36 25 4
gpt4 key购买 nike

我正在寻找一种方法来使用函数更改所有 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());

所有的面板和东西都被声明了,或者叫它什么。例如“私有(private) 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);

}

关于java - 使用instanceof改变JLabels的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43187365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com