簡體   English   中英

從JList中刪除項目

[英]Removing items from a JList

這是一個代碼,我想更改JList項,但是當我單擊打開按鈕並且JList.removeAll()運行時,我的JList不會刪除項...是什么問題?

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

如果您不相信,請進行測試。

您這樣做的方式是錯誤的。 使用構造函數new JList(j) ,只有一個“只讀模型”。

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:

您應該使用真實的模型,例如:

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);

}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM