javaswinglistselectionlistener

ListSelectionListener not changing panel


I want a ListSelectionListener event to change a JPanel. I know it is getting fired properly because the print statement is working, however the panel does not change at all.

DefaultListModel leftList = new DefaultListModel();
JList order = new JList(leftList);
order.addListSelectionListener(this);
JPanel configPanel = new JPanel();

public void valueChanged(ListSelectionEvent e) {
 if(e.getValueIsAdjusting()){
        int index = order.getSelectedIndex();
        System.out.println(leftList.getElementAt(index).toString());
        configPanel.removeAll();
        configPanel.repaint();
        configPanel.add(new JLabel("nice"));
        configPanel.repaint();
        }
    }

I threw in the second repaint simply because I was out of things to try, however it still did not work.


Solution

  • When you add components to a visible GUI the basic logic is:

    panel.remove(...);
    panel.add(...);
    panel.revalidate();
    panel.repaint();
    

    Basically all components have a size of (0, 0) when they are created so there is nothing to paint. You need to invoke revalidate() so the layout manager can give the components a size and location on the panel.