我需要一个静态实用程序方法来从List<T>
. 我遇到了两个问题。这是一个简短的测试程序:
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()的方法可以让我获取列表的索引而不是显示的字符串?
编辑:我也宁愿强制使用 JList 而不是组合框或 JOptionPane 想要的任何默认值。