2016-03-08 59 views
0

我有一个GUI,它包含包含与此组件相关的组件和标签的面板。标签创建并且永远不会改变,所以目前,我的构造函数只有JPanel.add()方法。Java - 在JPanel内部访问JLabel

//add label 
    toServerPanel.add(new JLabel("Your Message"), BorderLayout.NORTH); 
    //add component 
    toServerPanel.add(toServer, BorderLayout.SOUTH); 

这工作得很好,他们都很好匿名对象,但我现在想改变一些或所有应用程序中的标签的文本颜色。因为他们是匿名对象,所以他们不能通过他们的变量名访问,但同时我不想创建无穷无尽的变量JLabel

在当前情况下,是通过检查JPanel内的对象来访问JLabel对象的方法或函数? 另外,是否有某种循环会影响GUI上所有的JLabel对象?

谢谢, 马克

+0

*“标签创建和从来没有改变过” *:两个JLabel的颜色,当你点击按钮随机分配在'toServerPanel'获取它们来检索它们?如果你想用某个标识符查找它们,你可以将它们保存在一个'List'或者一个'Map'中。 – MadProgrammer

回答

0

如果您JLabel是在你的面板上只有一个组件,你可以做这样的事情:

JLabel lbl = (JLabel)toServerPanel.getComponent(0); 

和手柄lbl

+0

感谢你们,这种解决方案可以放到一个循环中,对所有的面板都这样做吗? – marcuthh

+0

当然,您也可以使用methog [getComponents()](https://docs.oracle.com/javase/8/docs/api/java/awt/Container.html#getComponents--)在所有组件。 – josivan

5

,你可以通过控制面板的所有组件循环:

for (Component jc : toServerPanel.getComponents()) { 
    if (jc instanceof JLabel) { 
     // do something 
    } 
} 

编辑
这里是我创建并测试了一个最小的工作示例。所以,这似乎是一个愚蠢的说法,那么你为什么不提供一个 -

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(); 
    } 
} 
+0

你好,尝试了这一点,标签似乎不受影响。任何想法,为什么这可能是? – marcuthh

+0

@marcuthh我已经添加了一个工作示例。如果标签不受影响,是否有可能该标签不是直接的孩子 - 例如,包裹在另一个面板? – MalaKa