0

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

2
  • 2
    Probably Map<FieldType,List<FieldNames>> is better than Arrays in this case Commented Jul 22, 2013 at 11:08
  • I second this. 2 arrays will be disjointed where as a map of some kind will allow you to link your names and types. Commented Jul 22, 2013 at 11:13

1 Answer 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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. let me give it a shot and get back to you.
@WandererofTime you're welcome. I've edited my answer in order to suggest one way (out of various ways) to retrieve the Component after your Map has been populated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.