貌似是jlist的bug

如例子代码中所示,对于jlist,第一次往model中addelement时正常,然后默认选中list中的第一条,第二次点击fresh时,程序先把model clear后再往里面addelement,这时速度就会非常慢,而如果默认选中的不是第一天记录,addelement就会正常,大家有遇到过这种情况的吗?


public class TestJList extends JFrame {
	private static final long serialVersionUID = 1L;
	JButton fresh = new JButton("fresh");
	JScrollPane jsp = new JScrollPane();
	JPanel panel = new JPanel();;
	DefaultListModel model = new DefaultListModel();
	Runnable runnable = null;
	Thread t = null;
	JList list = new JList(model);

	private TestJList() {
		init();
	}

	void init() {
		this.setTitle("JList test");
		this.setSize(300, 200);
		loadData();

		panel.setLayout(new BorderLayout());
		fresh.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				loadData();
			}
		});
		panel.add(fresh, BorderLayout.NORTH);

		jsp.getViewport().setView(list);
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		list.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				System.out.println("the item you have selected is :"
						+ e.getLastIndex());
			}
		});
		panel.add(jsp, BorderLayout.CENTER);

		this.getContentPane().add(panel);
		this.setVisible(true);
		this.pack();
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	void loadData() {
		fresh.setEnabled(false);
		if (model.size() != 0) {
			model.clear();
		}
		runnable = new Runnable() {
			public void run() {
				for (int i = 0; i < 1000; i++) {
					model.addElement("hello world:" + i);
				}
				list.setSelectionInterval(0, 0);
				SwingUtilities.invokeLater(new Runnable() {
					public void run() {
						fresh.setEnabled(true);
					}
				});
			}
		};
		SwingUtilities.invokeLater(runnable);
	}

	public static void main(String[] args) {
		new TestJList();
	}
}

你可能感兴趣的:(thread,jsp)