2016-01-16 30 views
-2

我有一个名为Car的类,该类具有如id,名称,价格,颜色和大小等属性。当我创建一个对象时,对于颜色和大小,我想要一个列表来从中选择属性值。我不希望用户写“黑”或“小”,我想在应用程序的某个地方找到它们。从列表中选择属性值-java

Car c1 = new Car(1, "Super Car", 152.5, "black", "small"); 

有没有人可以帮助我呢?

+0

也许你的意思是你想使用枚举的? –

+0

您可以为此创建枚举('Color','Size') – Andrew

+0

请更好地定义您的用例,因为例如它不清楚“user”是什么意思。这是使用您的API或使用您的应用程序的最终用户的开发人员吗? –

回答

0

然后,您应该有可供用户选择的值的列表。以下是颜色的例子(只是一个简单的例子,没有去太深成Java构建了每个方案):

List<String> color = new ArrayList<String>(); 
color.add("black"); 
color.add("white"); 
// etc 

Car c1 = new Car(1, "SuperCar", 152.5, color.get(userSelectedOptionIndex), "smal"); 

这里,userSelectedOptionIndex应该是用户选择的GUI选项的索引。

0

1)你可以使用一个类通过简单的字符串来保存您的常量:

public final class Constants { 

    private Constants() { 
     // restrict instantiation 
    } 

    public static final String COLOR_BLACK = "black"; 
    public static final String COLOR_WHITE = "white"; 

    public static final String SIZE_SMALL = "small"; 
    public static final String SIZE_LARGE = "large"; 
} 

用法:

Car c1 = new Car(1, "Super Car", 152.5, Constants.COLOR_BLACK, Constants.SIZE_SMALL) 

2)另一种方法是使用常量类枚举:

public final class Constants { 

    private Constants() { 
     // restrict instantiation 
    } 

    public static enum Color { White, Black }; 
    public static enum Size { Small, Large }; 
} 

用法:

Car c1 = new Car(1, "Super Car", 152.5, Constants.Color.White, Constants.Size.Small) 

3)但更好的方法(更多OOP批准)是单独定义枚举和丢弃常量类完全

public enum Color { 
    White, 
    Black 
} 

public enum Size { 
    Small, 
    Large 
} 

用法:

Car c1 = new Car(1, "Super Car", 152.5, Color.White, Size.Small) 

,倘若你,如果你有一个GUI元素,用户应该从中选择valuse,可以使用这些枚举值创建一个Array或List,然后填充您的GUI元素:

JavaFx 8示例:

Color[] values = Color.values(); 
ComboBox<Color> comboBox = new ComboBox<>(); 
comboBox.getItems().addAll(values); 

后来得到选择的值:

Color selectedColor = comboBox.getValue();