我用 Eclipse 的 Windowbuilder 创建了一个窗口。该窗口包含一个内容面板和内容面板中的两个滚动面板。我想用不同的方法将元素添加到两个滚动面板。我的代码看起来像这样(只是相关部分):
public window() {
contentPane = new JPanel(); // Plus some methods like setLayout or setBorder for the contentpane
JScrollPane scrollPane1 = new JScrollPane();
contentPane.add(scrollPane1);
JScrollPane scrollPane2 = new JScrollPane();
contentPane.add(scrollPane2);
}
public static void addItems(ArrayList<String> list)
{
Window w = new Window();
for(String s : list)
{
w.contentPane.scrollPane1.addElement(s);
/* Normally it should be something like this, but I just get access
to the contentPane and cannot add anything directly to the ScrollPanes. */
}
}
是否有任何特殊设置拒绝直接访问单个组件?
编辑:感谢@summerbulb,我对 -Method 进行了一些更改addItems
,现在看起来像这样。
public static void addItems(ArrayList<String> appList)
{
WindowAppsAndHardware w = new WindowAppsAndHardware();
Component[] components = w.contentPane.getComponents();
Component component = null;
for(String s : appList)
{
for (int i = 0; i < components.length; i++)
{
component = components[i];
if (component.getName().equals("scrollPane1"));
{
Label lbl = new Label();
lbl.setName(s);
component.addElement(lbl);
/*Here I want to add the Label to the component,
but component dont have the `addElement`-Method.*/
}
}
}
}