からオブジェクトを選択するための静的ユーティリティ メソッドが必要ですList<T>
。私は2つの問題に直面しています。短いテスト プログラムを次に示します。
package com.example.test.gui;
import java.util.Arrays;
import java.util.List;
import javax.swing.JOptionPane;
public class SelectionTest {
public interface NameExtractor<T> {
public String extractName(T object);
}
static public <T> T selectFromList(String message, List<T> list, NameExtractor<T> nameExtractor) {
String[] choices = new String[list.size()];
int i = 0;
for (T t : list)
choices[i++] = nameExtractor.extractName(t);
Object s = JOptionPane.showInputDialog(null, message, "",
JOptionPane.QUESTION_MESSAGE, null, choices, null);
System.out.println(s);
// crap, we get a string back. Now how do we get back the object in question?
return null;
}
static public void main(String[] args)
{
List<Integer> numbers = Arrays.asList(1,2,3,4,10);
System.out.println(selectFromList("Pick one", numbers, new NameExtractor<Integer>(){
@Override public String extractName(Integer object) {
return object.toString();
}
}));
}
}
表示された文字列ではなく、リストのインデックスを取得できるJOptionPane.showInputDialog()の代替手段はありますか?
編集:コンボボックスやJOptionPaneがデフォルトとして必要とするものではなく、JListの使用を強制したいと思います。