簡體   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