0

So in my code, I have a Frame with a MenuBar that lets me add Panels. One Panel has some TextFields through which I build Objects, add them to an ArrayList and then display them in a JList.

My issue is that when I press the button that builds the Object, the Panel isn't refreshing to immediately show the contents of the JList, I have to actually recall the Panel from the MenuBar for it to work.

So this is the part where I build the JList and fill it if the ArrayList exists (this part is in the Constructor of the Panel) :

        listModel = new DefaultListModel();
        if (!MainInterface.listCat.isEmpty()) {
            for (CategorieArticle c : MainInterface.listCat) {
                listModel.addElement(c.toString());
            }
        }
        list = new JList(listModel);

And this is the button method that builds the Objects and adds them to the ArrayList (this part is in the ActionListener method) :

    public void actionPerformed(ActionEvent e) {
        Object o = e.getSource();
        if (o == bEnr) {
            if (tfNoCat.getText().isBlank() || tfNomCat.getText().isBlank()) {
            } else {
                MainInterface.listCat.add(new CategorieArticle(tfNomCat.getText()));
                tfNoCat.setText("");
                tfNomCat.setText("");
                mainPanel.revalidate();
                mainPanel.repaint();
            }
        }
    }

The issue is that .revalidate() and .repaint() aren't refreshing the Panel for it to go through the first piece of code and fill the JList.

Any help would be very much appreciated.

Maroji
  • 1

1 Answers1

1
list = new JList(listModel);

The above code does nothing. You create a new JList but you never add it to the frame.

Don't keep creating the JList. The JList is only created once and added to a scrollpane which is added to the frame, when you initially create the components for the GUI.

To change the data displayed in the JList your only need to update the ListModel of the existing JList. The JList will automatically repaint itself.

mainPanel.revalidate();
mainPanel.repaint();

Also not needed since you never add any components to the panel in the ActionListener.

, add them to an ArrayList and then display them in a JList.

That is the real problem. There is no need for the ArrayList. The data is already stored in the ListModel. There is no need to have the data in two places.

Just add the data directly to the ListModel in your ActionListener.

//MainInterface.listCat.add(new CategorieArticle(tfNomCat.getText()));
CategorieArtical c = new CategorieArticle( tfNomCat.getText() );
listModel.addElement( c.toString() );
//MainInterface.listCat.add( c ); // if you really need the ArrayList for some other reason

You should create "listModel" as an instance variable in your class so it can be accessed in the ActionListener.

camickr
  • 321,443
  • 19
  • 166
  • 288