我需要一个静态工具方法来从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想要的默认值。
因为toString()不一定是我想要显示对象描述的方法。我在对象类外部使用NameExtractor接口。 – 2010-11-02 14:56:55
+1 for list.toArray()虽然,这是我没有想到的东西 – 2010-11-02 15:30:17