Java - 在JPanel中访问JLabel

mar*_*thh 1 java swing jlabel jpanel

我有一个GUI,用于保存包含组件和与此组件相关的标签的面板.标签是创建的,永远不会改变,所以目前我只是在JPanel.add()方法中有他们的构造函数.

    //add label
    toServerPanel.add(new JLabel("Your Message"), BorderLayout.NORTH);
    //add component
    toServerPanel.add(toServer, BorderLayout.SOUTH);
Run Code Online (Sandbox Code Playgroud)

这工作正常,它们可以作为匿名对象使用,但我现在想要更改应用程序中部分或全部标签的文本颜色.看到它们是匿名对象,它们不能通过变量名访问,但同时我不想创建无穷无尽的JLabel变量.

在目前的情况下,是JLabel通过检查内部对象来访问对象的方法或函数JPanel吗?或者,是否存在某种可能影响JLabelGUI上所有对象的循环?

谢谢,马克

Mal*_*aKa 6

您可以遍历Panel的所有组件:

for (Component jc : toServerPanel.getComponents()) {
    if ( jc instanceof JLabel ) {
        // do something
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑
这是我创建和测试的最小工作示例.单击按钮时,将随机分配两个JLabel的颜色:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class ComponentTest extends JFrame implements ActionListener {

    private JPanel mainPanel;
    private Random r;

    public ComponentTest() {
        super("TestFrame");

        r = new Random();
        mainPanel = new JPanel(new BorderLayout());
        mainPanel.add(new JLabel("I'm a Label!"), BorderLayout.NORTH);
        mainPanel.add(new JLabel("I'm a label, too!"), BorderLayout.CENTER);

        JButton triggerButton = new JButton("Click me!");
        triggerButton.addActionListener(this);
        mainPanel.add(triggerButton, BorderLayout.SOUTH);

        setContentPane(mainPanel);

        this.pack();
        this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Color c = new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256));
        for (Component jc : mainPanel.getComponents()) {
            if (jc instanceof JLabel) {
                JLabel label = (JLabel) jc;
                label.setForeground(c);
            }
        }
    }

    public static void main(String[] args) {
        new ComponentTest();
    }
}
Run Code Online (Sandbox Code Playgroud)