Search code examples
javaswingrefresh

How to refresh JScrollPane


My main frame contains JScrollPane which lists some objects. Through menu (pop up frame) I create new object and I want to list this object in the JScrollPane (which is created in a constructor of DemoFrame class). How can I do it?

Part of my constructor in DemoFrame

    ArrayList<Item> i = g.getAllItems(); 
    Vector allItemsVector = new Vector(i); 
    JList items = new JList(allItemsVector); 
    panel.add( new JScrollPane( items ))

In pop up frame I add new object to 'g' object in that case. Have I designed it wrong?


Solution

  • A lot depends on information that you haven't told us, for instance just what is the JScrollPane holding? A JTable? A JList? The key will be to update the component being held by the JScrollPane and then revalidate and repaint this component.

    Edit
    You need to have a reference to the JList, so it should be declared outside of your constructor. For instance:

    // 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 ))
       }
    

    Then later in your menu's listener code you can add an item to the items JList as needed.