0

我正在尝试构建一个表单生成类,我可能在我的逻辑语句的某个地方遇到了一个小故障。

你有两个字符串数组。

String[] fieldNames;
String[] fieldTypes;

它们的长度应该相同。fieldName[] 中的每个值对应于 fieldTypes[] 数组中的一个值。

我想根据 fieldTypes 数组中规定的值创建各种字段,并为创建的字段分配 fieldNames 数组中指定的名称。例如

String[] fieldNames = {"Name", "Phone", "Gender"}
String[] fieldTypes = {"TextFied","ComboBox", "RadioButton"} 

字段类型和名称可能会有所不同。他们可以是你希望他们成为的任何人。

现在,使用上述信息,我如何将 fieldNames 分配给 fieldTypes,以便我可以在数据处理中使用它们?IE

TextField name = new TextField();
ComboBox phone = new ComboBox();
RadioButton gender = new RadioButton();

我已经考虑了一个星期了,网上似乎没有任何解决方案。或者更确切地说,我一直找不到。我有人可以指出我正确的方向,我会很高兴

4

1 回答 1

1

You could use a Map of String and Class, as such:

// This is for AWT - change class bound to whatever super class or interface is 
// extended by the elements of the framework you are using
Map<String, Class<? extends Component>> fields = new LinkedHashMap<String, Class<? extends Component>>();
fields.put("Name", TextField.class);

The Map is a LinkedHashMap so you can keep the order of the keys.

Once you retrieve a value through the get method, you can get the class of the desired component and act upon.

Edit

Here's how to retrieve the component through reflexion. Note that it's not the only solution and might not be the "cleanest"...

try {
    Component foo = fields.get("Name").newInstance();
    System.out.println(foo.getClass());
}
catch (Throwable t) {
    // TODO handle this better
    t.printStackTrace();
}

Output:

class java.awt.TextField
于 2013-07-22T11:13:50.197 回答