【问题标题】:Creating Textfields by loop通过循环创建文本字段
【发布时间】:2016-01-02 03:53:07
【问题描述】:

我在volstextfield 中有以下项目列表,然后我将其传递给createGUI。我想创建一个名称为vol1HH1,vol1HH2JTextFields 列表。我收到一个错误Incompatible types: JTextField cannot be converted to volstextfield,有人可以帮忙吗?

public enum volstextfield {
    vol1HH1, vol1HH2
}

public void createGUI() {
    for (volstextfield direction : EnumSet.allOf(volstextfield.class)) {
        System.out.println(direction);
        direction = new JTextField(5); //i get an error here incompatible types: JTextField cannot be converted to volstextfield
    }
}

【问题讨论】:

    标签: java for-loop jtextfield


    【解决方案1】:

    您的方向变量是enum 类型。您不能将JTextField 分配给enum。试试看

    JTextField textfield = new JTextField(direction.getName());
    

    或者使用

    JTextField textfield = new JTextField();
    textfield.setName(direction.getName());
    

    【讨论】:

    • .getName() 似乎不起作用我得到错误找不到符号符号:方法 getname() 位置:volstextfield 类型的变量方向
    • 您也需要在枚举中进行位修改,尝试定义 vol1hh1("vol1hh1") 并将名称变量添加到枚举并添加 toString 以返回名称。它会起作用的。
    • 我使用 .name,我现在正在查看您将名称定义为 vol1hh1("vol1hh1") 的建议
    • 我不清楚为什么定义这样的名称会有所不同?或者怎么做?
    【解决方案2】:

    枚举本身就是一个类型,你能做的最接近的事情是:

     // The Amount of JTextField is enum' length 
      JTextField direction[] = new JTextField[volstextfield .values().length]; 
            int i=0;
    
            for ( volstextfield v :volstextfield.values()) {
                direction [i++] = new JTextField(v.name());
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-30
      • 2020-07-27
      • 2016-11-04
      • 2022-01-03
      • 1970-01-01
      • 2013-05-04
      • 2021-02-27
      相关资源
      最近更新 更多