我正在尝试向我的空JList添加一个新元素,但它没有出现。我在EDT上运行它(我对该主题的信息很少)
public void populateProjectsList(List<Project> projectsList2) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
DefaultListModel<String> listModel = (DefaultListModel) projectsList.getModel();
listModel.clear();
for (Project project : projectsList2) {
System.out.println(project.id + ") " + project.name);
listModel.addElement(project.id + ") " + project.name);
}
}
});
}
System.out.println有效,我看到了我希望添加的正确输出,但列表仍然是空的。我在动作监听器中尝试了listModel.addElement,但它确实有效。
答案 0 :(得分:0)
例如,从ListSelectionListener调用时,您的代码可以正常工作,请参见下文。
我的猜测是你正确地将项目添加到JList,但是看不到它们,因为JList的维度很小,无法看到它的内容。处理窗口中组件的布局,或者在将其添加到窗口时将一些数据放入JList。当然,这可能是其他原因。
一个工作示例
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Main
{
public static void main(String args[])
{
new Main();
}
public Main()
{
JFrame fr = new JFrame("Hello");
DefaultListModel<String> model = new DefaultListModel<String>();
model.addElement("hello");
model.addElement("hi");
model.addElement("ola");
projectsList = new JList<>(model);
fr.add(projectsList);
fr.pack();
fr.setVisible(true);
projectsList.addListSelectionListener(
new ListSelectionListener()
{
@Override
public void valueChanged(ListSelectionEvent e)
{
List<Project> toAdd = new ArrayList<>();
toAdd.add(new Project(7, "seven"));
toAdd.add(new Project(10, "ten"));
toAdd.add(new Project(4, "four"));
populateProjectsList(toAdd);
projectsList.removeListSelectionListener(this);
}
}
);
}
JList projectsList;
private void populateProjectsList(List<Project> projectsList2)
{
EventQueue.invokeLater(
new Runnable() {
@Override
public void run()
{
DefaultListModel<String> listModel = (DefaultListModel<String>) projectsList.getModel();
listModel.clear();
for (Project project : projectsList2)
{
System.out.println(project.id + ") " + project.name);
listModel.addElement(project.id + ") " + project.name);
}
}
}
);
}
private class Project
{
int id;
String name;
public Project(int id, String name)
{
this.id = id;
this.name = name;
}
}
}