Reputation: 1
I'm trying to build a form generating class and i might have hit a glitch somewhere in my logic statement.
You have two string arrays.
String[] fieldNames;
String[] fieldTypes;
Both their lengths should be the same. Each value in the fieldName[] corresponds to a value in the fieldTypes[] array.
I want to create various fields depending on the values stated in the fieldTypes array and assign the created fields the name specified in the fieldNames array.e.g.
String[] fieldNames = {"Name", "Phone", "Gender"}
String[] fieldTypes = {"TextFied","ComboBox", "RadioButton"}
The field types and names can vary. They can be whatever you want them to be.
Now, using the above info, how do i assign the fieldNames to the fieldTypes so I can use them in the data processing? i.e
TextField name = new TextField();
ComboBox phone = new ComboBox();
RadioButton gender = new RadioButton();
I've been mulling this over for a week now and there doesn't seem to be any solution to this online. Or rather I haven't been able to find one. I someone could point me in the right direction i'll be greatful
Upvotes: 0
Views: 389
Reputation: 48404
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
Upvotes: 1