Java 如何刷新JScrollPane

Java 如何刷新JScrollPane,java,swing,refresh,Java,Swing,Refresh,我的主框架包含JScrollPane,其中列出了一些对象。通过菜单(弹出框),我创建了一个新对象,我想在JScrollPane中列出这个对象(它是在DemoFrame类的构造函数中创建的)。我怎么做 DemoFrame中我的构造函数的一部分 ArrayList<Item> i = g.getAllItems(); Vector allItemsVector = new Vector(i); JList items = new JList(allItemsV

我的主框架包含JScrollPane,其中列出了一些对象。通过菜单(弹出框),我创建了一个新对象,我想在JScrollPane中列出这个对象(它是在DemoFrame类的构造函数中创建的)。我怎么做

DemoFrame中我的构造函数的一部分

    ArrayList<Item> i = g.getAllItems(); 
    Vector allItemsVector = new Vector(i); 
    JList items = new JList(allItemsVector); 
    panel.add( new JScrollPane( items ))
ArrayList i=g.getAllItems();
向量allItemsVector=新向量(i);
JList items=新的JList(allItemsVector);
panel.add(新的JScrollPane(项目))

在弹出框中,我将新对象添加到“g”对象中。我设计错了吗?

很大程度上取决于您没有告诉我们的信息,例如,JScrollPane包含什么?JTable?记者?关键是更新JScrollPane持有的组件,然后重新验证并重新绘制该组件

编辑
您需要有对JList的引用,因此它应该在构造函数之外声明。例如:

// GUI class
public class GuiClass {
   private JList items; // declare this in the *class*

   // class's constructor
   public GuiClass() {
     ArrayList<Item> i = g.getAllItems(); 
     Vector allItemsVector = new Vector(i); 

     // JList items = new JList(allItemsVector); // don't re-declare in constructor
     items = new JList(allItemsVector); 

     panel.add( new JScrollPane( items ))
   }
//GUI类
公共类GuiClass{
private JList items;//在*类中声明*
//类的构造函数
公共类(){
ArrayList i=g.getAllItems();
向量allItemsVector=新向量(i);
//JList items=new JList(allItemsVector);//不要在构造函数中重新声明
项目=新的JList(allItemsVector);
panel.add(新的JScrollPane(项目))
}

然后,在菜单的侦听器代码中,您可以根据需要向items JList添加一个项目。

这对我来说也是一个问题。一个快速的解决方法是从面板中删除JScrollPane,进行更改,然后读取它。许多人可能认为它效率低下,但运行时没有重大更改

JPanel panel = new Jpanel();
JList list = new JList({"this", "is", "a test", "list"});
JScrollPane sPane = new JScrollPane();

public void actionPerformed(ActionEvent e) {
  if (resultsPane!=null){
panel.remove(sPane);
  }

  sPane = updatePane(list);         
  panel.add(sPane);
}

public void updatePane(String[] newListItems) {
  DefaultListModel model = new DefaultListModel();  
  for(int i = 0; i < newListItems.length; i++) {
    model.addElement(newListItems[i]);
  }

JList aList = new JList(model);
JScrollPane aPane = new JScrollPane(aList);

}
JPanel面板=新的JPanel();
JList list=新JList({“this”、“is”、“a test”、“list”});
JScrollPane=新的JScrollPane();
已执行的公共无效操作(操作事件e){
如果(resultsPane!=null){
面板。移除(sPane);
}
sPane=更新面板(列表);
面板。添加(sPane);
}
public void updatePane(字符串[]newListItems){
DefaultListModel=新的DefaultListModel();
for(int i=0;i
replicate of-有完整答案的检查发布日期sherlock。