这是一个代码,我想更改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);
}
}
如果你不相信,请测试。
答案 0 :(得分:1)
你这样做的方式是错误的。使用构造函数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);
}
}