简体   繁体   English

如何在对话框中使用枚举使用JComboBox

[英]how to use JComboBox using Enum in Dialog Box

I define enums: 我定义枚举:

enum itemType {First, Second, Third}; 枚举itemType {第一,第二,第三};

public class Item 公共课项

{ {

private itemType enmItemType; 私人itemType enmItemType;

... ...

} }

How do I use it inside Dialog box using JComboBox? 如何在使用JComboBox的对话框中使用它? Means, inside the dialog box, the user will have combo box with (First, Second, Third). 意味着,在对话框中,用户将具有带有(第一,第二,第三)的组合框。 Also, is it better to use some sort of ID to each numerator? 另外,对每个分子使用某种ID更好吗? (Integer) (整数)

thanks. 谢谢。

This is the approach I have used: 这是我使用的方法:

enum ItemType {
    First("First choice"), Second("Second choice"), Third("Final choice");
    private final String display;
    private ItemType(String s) {
        display = s;
    }
    @Override
    public String toString() {
        return display;
    }
}

JComboBox jComboBox = new JComboBox();
jComboBox.setModel(new DefaultComboBoxModel(ItemType.values()));

Overriding the toString method allow you to provide display text that presents the user with meaningful choices. 覆盖toString方法使您可以提供显示文本,为用户提供有意义的选择。

Note: I've also changed itemType to ItemType as type names should always have a leading cap. 注意:我也将itemType更改为ItemType因为类型名称应始终带有前导上限。

JComboBox combo = new JComboBox(itemType.values());

Assuming you know how to code a dialog box with a JComboBox, following is something you can do to load Enum values on to a combo box: 假设您知道如何使用JComboBox编码对话框,则可以执行以下操作以将Enum值加载到组合框:

enum ItemType {First, Second, Third};    
JComboBox myEnumCombo = new JComboBox();
myEnumCombo.setModel(new DefaultComboBoxModel(ItemType.values());

Then to get value as enum you could do 然后获得枚举值,您可以做

(ItemType)myEnumCombo.getSelectedItem();

There is no need to assign IDs to enums unless your application logic badly needs to have some meaningful ID assigned. 除非您的应用程序逻辑非常需要分配一些有意义的ID,否则无需为枚举分配ID。 The enum itself already has a unique ID system. 枚举本身已经具有唯一的ID系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM