如何在JComboBox中显示信息,但选择不同的信息进行后台操作
How to display information in a JComboBox, but choose different information for backend operation
我有一个代码列表,与不同的操作相关。
我想显示易于阅读的信息供用户选择,但是当用户选择他们想要的内容时,当他们单击按钮提交时,后端操作与代码列表相关联。
示例:
Displayed | Backend
--------------------|------------------------------------------
Hardware Inventory | "{00000000-0000-0000-0000-000000000001}"
Software Inventory | "{00000000-0000-0000-0000-000000000002}"
创建您自己的 class,使用 toString() 方法中返回的不太直观的值和易于阅读的值。然后将您的值添加到组合框。
使用 getSelectedItem() 检索值。
最佳答案取决于那些标签-代码对是否变化很大。为了灵活性:
public class FooOperation {
private final String label;
private final String internalCode;
public FooOperation(String label, String internalCode) {
this.label = label;
this.internalCode = internalCode;
}
public String toString() { return label; } // human-readable, displayed in CB
public String getCode() { return internalCode; } // ugly but true
}
然后,您可以在应用程序启动时从文件加载它们,并给定一个您以某种方式加载的 FooOperation[]
,您可以通过
显示它
JComboBox options = new JComboBox(availableOperations);
选项会根据其toString()
显示,但一旦选择,您可以轻松确定其内码:
FooOption[] selected = options.getSelectedItems();
if (selected.length == 1) {
System.err.println("you have selected " + selected[0].getCode());
}
如果您不需要在启动时灵活地从文件或 class 路径资源加载它们,您也可以选择 enum
(只需使用 public enum FooOperation
并初始化枚举中所有可能的操作 class)。这更简单(没有文件),但更难扩展(您必须触摸代码并重新编译才能更改可用选项)
我有一个代码列表,与不同的操作相关。 我想显示易于阅读的信息供用户选择,但是当用户选择他们想要的内容时,当他们单击按钮提交时,后端操作与代码列表相关联。 示例:
Displayed | Backend
--------------------|------------------------------------------
Hardware Inventory | "{00000000-0000-0000-0000-000000000001}"
Software Inventory | "{00000000-0000-0000-0000-000000000002}"
创建您自己的 class,使用 toString() 方法中返回的不太直观的值和易于阅读的值。然后将您的值添加到组合框。 使用 getSelectedItem() 检索值。
最佳答案取决于那些标签-代码对是否变化很大。为了灵活性:
public class FooOperation {
private final String label;
private final String internalCode;
public FooOperation(String label, String internalCode) {
this.label = label;
this.internalCode = internalCode;
}
public String toString() { return label; } // human-readable, displayed in CB
public String getCode() { return internalCode; } // ugly but true
}
然后,您可以在应用程序启动时从文件加载它们,并给定一个您以某种方式加载的 FooOperation[]
,您可以通过
JComboBox options = new JComboBox(availableOperations);
选项会根据其toString()
显示,但一旦选择,您可以轻松确定其内码:
FooOption[] selected = options.getSelectedItems();
if (selected.length == 1) {
System.err.println("you have selected " + selected[0].getCode());
}
如果您不需要在启动时灵活地从文件或 class 路径资源加载它们,您也可以选择 enum
(只需使用 public enum FooOperation
并初始化枚举中所有可能的操作 class)。这更简单(没有文件),但更难扩展(您必须触摸代码并重新编译才能更改可用选项)