0

我有一个要在 Swing 中显示的项目列表。为简单起见,假设每个项目仅包含一个名称。我希望用户能够通过将它们拖放到彼此上方/下方来订购这些项目。实现这一目标的最佳方法是什么?

或者,这是否可以通过使用 JList 来完成,该 JList 带有一个“向上”和“向下”按钮,可以在列表中向上/向下移动所选项目。这需要在每次点击时立即更新图形显示(我不知道如何执行此操作),并通过按当前顺序获取列表中的项目来保存新订单(我也不知道该怎么做)。

或者拖放解决方案是否更可行?

4

2 回答 2

2

使用您提到的解决方案可能更容易实现这JList一点,所以我会给您一些指示(我对 D&D 不是很有经验)。

基本上,您希望拥有三个组件:aJList和两个(一个向上,一个向下)JButtons。您可能还需要一个自定义列表模型。如果您不熟悉模型或列出模型,请查看本教程。否则,请继续阅读。

在列表模型类(例如ReorderableListModel)中,继续定义两个方法:public void moveUp(int index)public void moveDown(int index)

的代码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将为您进行更新。

于 2013-03-11T20:54:32.977 回答
0

仅使用 swing 很难实现的功能。你听说过 JavaFX 吗?如果您想在桌面应用程序中实现更多动态功能,它是一个很好的图形框架,请查看这篇文章:http ://docs.oracle.com/javase/tutorial/uiswing/dnd/index.html

在这里,您将能够找到包含更多信息的链接以及一些示例。最好的祝福。

于 2013-03-11T20:52:37.677 回答