如何提取所选值??我的意思是如果";Vital">是由用户选择的,我需要得到值0,或者>的值1;奥林匹克
Object[] possibleValues = { "Vital", "Olympic", "Third" };
Object selectedValue = JOptionPane.showInputDialog(null,
"Choose one", "Input",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
我以前有一个代码,它可以很好地与showConfirmDialog框配合使用。
int choice = JOptionPane.showConfirmDialog(null, "Click Yes for Rectangles, No for Ovals");
if (choice==2)
{
return ;
}
if (choice==0)
{
choice=5;
}
if (choice==1)
{
choice=6;
}
Shapes1 panel = new Shapes1(choice);
这很有效。
如果它为您提供文本表示,请添加一个方法将文本值转换为数字索引,如果您需要的话。一个O(1(的方法是提前创建一个映射,如果这些值是恒定的:
Map<String, Integer> valueToIndex = new HashMap<>();
valueToIndex.put("Vital", 0);
valueToIndex.put("Olympic", 1);
valueToIndex.put("Third", 2);
那只是
int index = valueToIndex.get((String) selectedValue)
如果你只会做一次,那么就不用麻烦创建地图了。只需迭代可能的值,直到找到selectedValue
的索引
int indexFor(Object selectedValue, Object possibleValues) {
for (int i = 0; i < possibleValues.length; i++) {
if (possibleValues[i].equals(selectedValue)) {
return i;
}
}
throw new RuntimeException("No index found for " + selectedValue);
}
然后调用这个方法:
int index = indexFor(selectedValue, possibleValues);