我有一个使用 NetBeans IDE 的设计模式创建的 jList(名为 JList1),我想使用辅助类将项目添加到该列表,该辅助类解析一个大的 xml 列表并从中获取数据。我的问题是我真的不明白该怎么做,我已经尝试了很多不同的代码,也尝试过使用模型,但无法正确完成。我是 java 新手(也是编程新手),如果我做类似的事情我不明白
String[] ar = {"one", "two", "three"};<br/>
JList Jlist1 = new JList(ar);
这创建了一个新的 jList 而不是使用我已经创建的,不是吗?
最佳答案
created using the Desing mode from NetBeans IDE,
成为由
生成的代码的囚犯可能不是个好主意向 DefaultListModel 添加一个新项目
and I want to add items to that list using a secondary class which parses a big xml list and gets the data from it.
听起来您对 Concurency in Swing 有疑问, 必须在美国东部时间更新已经可见的 Swing GUI
使用
SwingWorker#publish()
进行长期而艰巨的工作(解析大型 xml 列表并从中获取数据。)
例如向DefaultListModel添加一个新的Item
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Testing extends JFrame {
private static final long serialVersionUID = 1L;
private DefaultListModel listModel = new DefaultListModel();
private JList list = new JList(listModel);
private int currentSelectedRow = 0;
private int xX = 0;
public Testing() {
setLocation(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
for (int x = 0; x < 9; x++) {
listModel.addElement("" + x);
xX++;
}
JScrollPane sp = new JScrollPane(list);
add(sp, BorderLayout.CENTER);
JButton btn1 = new JButton("Reset Model CastingModel");
add(btn1, BorderLayout.NORTH);
btn1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
list.clearSelection();
DefaultListModel model = (DefaultListModel) list.getModel();
model.removeAllElements();
// note Swing GUI by default to freeze if is removed more that
// 999 elemets from the JList or its underlaying XxxListModel,
// to use repeatly Actions from SwingTimer on short period
for (int x = 0; x < 9; x++) {
model.addElement("" + (x + xX));
xX++;
}
list.setModel(model);
}
});
JButton btn2 = new JButton("Reset Model directly from Model");
add(btn2, BorderLayout.SOUTH);
btn2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
list.clearSelection();
listModel.removeAllElements();
for (int x = 0; x < 9; x++) {
listModel.addElement("" + (x + xX));
xX++;
}
}
});
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Testing().setVisible(true);
}
});
}
}
关于java - 将项目添加到另一个类的现有 jlist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18270799/