0

目前我有这种代码方法,它接受文本字段的变量名并读取输入的内容

public Object getValue(Component c) {

          Object val = null;

          if (c instanceof CustomWizardComponent) {
             val = ((CustomWizardComponent) c).getValue();
          } else if (c instanceof JTextComponent) {
             val = ((JTextComponent) c).getText();
          } else if (c instanceof AbstractButton){
             val = ((AbstractButton) c).isSelected();
          } else if (c instanceof JComboBox){
             val = ((JComboBox) c).getSelectedItem();
          } else if (c instanceof JList){
             val = ((JList) c).getSelectedValues();
          } else {
             log.warn("Unknown component: "+c);
          }

          return val;
       }


 JTextField text = new JTextField();
 text.setName("text");
 add(text);
 System.out.print("The component value is  "+ page.getValue(text));

现在我已将名称设置为与 JTextField 组件名称相同的名称。如何将该字符串转换为组件以读取相同的字段?我理想的新方法应该能够接受 String 然后转换为组件并获取值

 public String getValue(String item)
    {
        Component c=item;
          Object val = null;

      if (c instanceof CustomWizardComponent) {
         val = ((CustomWizardComponent) c).getValue();
      } else if (c instanceof JTextComponent) {
         val = ((JTextComponent) c).getText();
      } else if (c instanceof AbstractButton){
         val = ((AbstractButton) c).isSelected();
      } else if (c instanceof JComboBox){
         val = ((JComboBox) c).getSelectedItem();
      } else if (c instanceof JList){
         val = ((JList) c).getSelectedValues();
      } else {
         log.warn("Unknown component: "+c);
      }
      return val.toString();
     }

 JTextField textstring = new JTextField();
 text.setName("textstring");
 add(text);
 System.out.print("The component value is  "+ page.getValue("textstring"));
4

1 回答 1

1

根据经验,您可以使用Component#setName()和维护 a ,它可以让您使用返回的 by作为键来按名称Map<String, Component>查找 a 。ComponentStringComponent#getName()

从理论上讲,您可能希望查看更高级别的抽象,例如可能由向导框架提供的抽象。

于 2013-10-04T11:11:33.360 回答