[英]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? 这是一个代码,我想更改
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);
}
}
if you don't believe that , please test. 如果您不相信,请进行测试。
The way you do it is wrong. 您这样做的方式是错误的。 With your constructor
new JList(j)
there is only a "read- only model". 使用构造函数
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:
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);
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.