1

我用 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.*/
       } 
    }
    }
}
4

2 回答 2

1

尽管您最初的想法可能看起来很直观,但当您想到它时,它就不是真的。

w.contentPane工作正常,Window您的班级也是如此,并且contentPane是该班级的成员。但contentPane.add(scrollPane1);不添加scrollPane1contentPane.

你需要的是:

Component[] components = w.contentPane.getComponents(); 
Component component = null; 
for (int i = 0; i < components.length; i++) 
{ 
   component = components[i]; 
   if (component == scrolPane1) 
   { 
      component.addElement(s);
   } 
} 

编辑:(在 OP 编辑​​了他的问题之后)
这个答案状态(基于JScrollPane API)你不应该将元素添加到JScrollPane. 相反,您应该这样做:

JPanel view = (JPanel)scrollPane.getViewPort().getView();
view.addItem(s);
于 2013-10-31T17:43:36.173 回答
0

我不确定,因为我以前没有这样做过,但看起来您正在尝试访问窗口上的 contentPane,但是您的代码中没有将 contentPane 附加到窗口的位置,所以这就是为什么您将无法访问它的孩子。

于 2013-10-31T17:41:06.207 回答