简体   繁体   English

从 JList 中删除一个元素

[英]Remove an element from JList

I try to remove selected element from jList, and get exception:我尝试从 jList 中删除选定的元素,并得到异常:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1 >= 0
        at java.util.Vector.elementAt(Vector.java:447)
        at javax.swing.DefaultListModel.remove(DefaultListModel.java:493)
        at gui.Back.jButton2ActionPerformed(Back.java:410)
        at gui.Back.access$300(Back.java:9)
        at gui.Back$5.actionPerformed(Back.java:146)

My code:我的代码:

DefaultListModel dlm = (DefaultListModel) jList1.getModel();
//System.out.println(dlm.getSize());
dlm.remove(jList1.getSelectedIndex()); //removeElementAt(int i) don't work too
jList1.setModel(dlm);

It's strange, because dlm.getSize();这很奇怪,因为 dlm.getSize(); returns 2.返回 2。

What I've doing wrong?我做错了什么?

The way I would do it is as follows:我会这样做的方式如下:

final int index = mylist.getSelectedIndex();

if (index >= 0) {
((DefaultListModel) mylist.getModel()).removeElementAt(index);
}

You don't need to re-set the ListModel again once data has been removed.删除数据后,您无需再次重新设置 ListModel。

Read the JList API and follow the link to the Swing tutorial on "How to Use Lists" for a working example that does this.阅读 JList API 并按照有关“如何使用列表”的 Swing 教程的链接获取执行此操作的工作示例。

Then compare your code with the working code to see what the difference is.然后将您的代码与工作代码进行比较,看看有什么不同。

We can't tell you the problem based on a few lines of code.我们无法根据几行代码告诉您问题。

I've also experienced this issue multiple times.我也多次遇到过这个问题。 Inspection at variable breakpoints reveal the returned index value < (size - 1) , so within parameters that would NOT expect to throw an IOOB Exception .在变量断点处检查显示返回的index value < (size - 1) ,因此在不期望抛出IOOB Exception I haven't been able to figure out the cause.我一直无法弄清楚原因。

However, I have managed an acceptable workaround, which is to keep my own external model of the the data in an ArrayList and edit that.但是,我管理了一个可接受的解决方法,即在ArrayList保留我自己的数据外部模型并对其进行编辑。 Then, convert to an array and update through the list.setListData() method.然后,转换为数组并通过list.setListData()方法进行更新。 Not very efficient, but functional and the only way I've found to completely preserve the integrity of the data.效率不高,但功能齐全,也是我发现完全保持数据完整性的唯一方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM