目前我有这种代码方法,它接受文本字段的变量名并读取输入的内容
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"));