あなたが言及したソリューションでこれを実装する方がおそらく簡単なJList
ので、それについていくつかの指針を示します(私はD&Dの経験があまりありません)。
基本的に、aJList
と 2 つの (1 つが上、もう 1 つが下)JButton
の 3 つのコンポーネントが必要です。また、おそらくカスタム リスト モデルも必要になるでしょう。モデルまたはリスト モデルに慣れていない場合は、このチュートリアルを確認してください。それ以外の場合は、読み進めてください。
リスト モデル クラス (例: ) で、とReorderableListModel
の 2 つのメソッドを定義します。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
更新を行います。