我有一个要在 Swing 中显示的项目列表。为简单起见,假设每个项目仅包含一个名称。我希望用户能够通过将这些项目拖放到彼此的上方/下方来排序。实现这一目标的最佳方法是什么?
或者,这可以通过使用 JList 来完成,其中带有“向上”和“向下”按钮,可以在列表中向上/向下移动所选项目。这将需要在每次点击时立即更新图形显示(我不知道如何执行此操作),并通过按当前顺序获取列表中的项目来保存新订单(我也不知道如何执行此操作) )。
或者拖放解决方案可能更可行?
最佳答案
使用您提到的 JList
解决方案来实现这一点可能会更容易,因此我将为您提供一些指导(我对 D&D 不是很有经验)。
基本上,您需要三个组件:一个 JList
和两个(一上一下)JButton
。您可能还需要一个自定义列表模型。如果您不熟悉型号或列出型号,请查看this tutorial 。否则,请继续阅读。
在列表模型类(例如,ReorderableListModel
)中,继续定义两个方法:public void moveUp(int index)
和 public void moveDown( int 索引)
。
moveUp
的代码如下:
if (index > 0) { // error checking
// Swap the given index with the previous index.
// (where `list` is the name of your list variable)
Collections.swap(list, index, index - 1);
}
// Finally, notify the `JList` that the list structure has changed.
fireContentsChanged(this, index - 1, index);
moveDown
类似:
if (index < getSize() - 1) {
Collections.swap(list, index, index + 1);
}
fireContentsChanged(this, index, index + 1);
现在,我们需要实现按钮的操作监听器。对于向上按钮,请尝试以下监听器代码:
// First, move the item up in the list.
listModel.moveUp(list.getSelectedIndex());
// Now, set the selection index to keep the same item selected.
//
// If you use the default list selection interval, setting the index to -1
// will do nothing (so it's okay, we don't need error checking here).
list.setSelectedIndex(list.getSelectedIndex() - 1);
添加类似的“下移”方法即可完成!
关于“每次点击时立即更新图形显示”,这就是模型类中的 fireContentsChanged
方法的作用。 JList
将为您进行更新。
关于java - 在 Swing 中拖放以订购项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15348241/