Java 如何根据来自GUI组件的值获得不同的行为?

Java 如何根据来自GUI组件的值获得不同的行为?,java,Java,我在GUI应用程序上有一个文本框,用户可以在其中设置两个值“productsupport”或“productLocal” 在我的服务类中,我正在检查类型是否为productSupport,是否执行其他操作 有没有更好的方法来检查来自GUI组件的这些值 class ProductService{ void handle(String type){ if(type.equals("productSupport"){ // //do something } else if(type.e

我在GUI应用程序上有一个文本框,用户可以在其中设置两个值“productsupport”或“productLocal”

在我的服务类中,我正在检查类型是否为productSupport,是否执行其他操作 有没有更好的方法来检查来自GUI组件的这些值

class ProductService{

 void handle(String type){
  if(type.equals("productSupport"){ // 
   //do something
}
else if(type.equals("productLocal"){
//do something else
}
}

}

您没有指定它是什么类型的UI,但一般来说,我不会使用文本框,以防用户可以在两件事之间进行选择。使用下拉框或组合框更有意义。作为框中的项目,我将使用枚举值:

enum Type {
    PRODUCT_SUPPORT("Product support"),
    PRODUCT_LOCAL("Product local");

    final String label;

    Type(String label) {
        this.label = label;
    }
}

这个看起来不错。你有什么问题?我不喜欢在服务类中硬编码值的方式,那么你不喜欢吗?使用枚举类?您使用的库或平台是什么?它是javafx、swing、awt还是类似的东西……它也是硬编码字符串中非常常见的常量。。。然后使用开关
class ProductService {
    void handle(Type type) {
        switch(type) {
            case PRODUCT_LOCAL:
                //do somethinf
                break;
            case PRODUCT_SUPPORT:
                //do something els3
        }
    }
}