Search code examples
javaswingjlist

Removing items from a JList


here is a code , I want to change JList items, but when i click on open button and JList.removeAll() runs , my JList doesn't remove items... what is the problem?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class JListTest {
    public static void main(String[] args) {
        String[] j = {"item1","item2","item3"};
        final JList list = new JList(j);

        JButton open = new JButton("open");
        open.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                list.removeAll();
            }
        });

        JFrame frame = new JFrame();
        frame.setSize(400, 400);
        Container con = frame.getContentPane();
        con.setLayout(new BorderLayout());
        con.add(open,BorderLayout.LINE_START);
        con.add(list,BorderLayout.CENTER);
        con.add(new JScrollPane(list));
        frame.setVisible(true);
    }
}

if you don't believe that , please test.


Solution

  • The way you do it is wrong. With your constructor new JList(j) there is only a "read- only model".

    http://docs.oracle.com/javase/7/docs/api/javax/swing/JList.html It's easy to display an array or Vector of objects, using the JList constructor that automatically builds a read-only ListModel instance for you:

    You should use a real Model for it like:

    public class JListTest {
    
    
    public static void main(String[] args) {
    
        DefaultListModel<String> model = new DefaultListModel<>();
        model.addElement("item1");
        model.addElement("item2");
        model.addElement("item3");
        final JList<String> list = new JList<String>(model);
    
        JButton open = new JButton("open");
        open.addActionListener(new ActionListener()
    
        {
            public void actionPerformed(ActionEvent e) {
                DefaultListModel<String> model = (DefaultListModel<String>) list.getModel();
                model.removeAllElements();
            }
        });
        JFrame frame = new JFrame();
        frame.setSize(400, 400);
        Container con = frame.getContentPane();
        con.setLayout(new BorderLayout());
    
        con.add(open, BorderLayout.LINE_START);
        con.add(list, BorderLayout.CENTER);
        con.add(new JScrollPane(list));
        frame.setVisible(true);
    
    }
    

    }