gpt4 book ai didi

java - 从 JList 中删除项目

转载 作者:行者123 更新时间:2023-12-01 11:30:43 24 4
gpt4 key购买 nike

这是一段代码,我想更改 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使用 JList 构造函数可以轻松显示对象数组或 Vector,该构造函数会自动为您构建只读 ListModel 实例:

您应该使用真实的模型,例如:

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

}

}

关于java - 从 JList 中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30421350/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com