I have a method that accepts only a String.
public void setVerticalAlignment(String align) {
...
gd.verticalAlignment = align; // accepts only
Why are you using a text field? There are only a few legal choices for alignments, so you should really use something like a JComboBox instead. You could store custom objects in the JComboBox so that they display the named constant but also store the integer constant:
public class SwingAlignOption {
public final String name;
public final int value;
public SwingAlignOption(String name, int value) {
this.name = name;
this.value = value;
}
public String toString() { return name; }
}
Then you can add instances to the combo-box like comboBox.addItem(new SwingAlignOption("TOP", SWT.TOP))
.
Note that JComboBox changed between Java 6 and 7. In the Java 7 libraries JComboBox is generic, which makes it easier to store custom objects like this inside and retrieve their values later. In Java 6 you'll have to use a cast when you access the selected value.
If you use Java 7 you can always use switch
on Strings:
switch (align) {
case "SWT.TOP":
gd.verticalAlignment = SWT.TOP;
/* etc */
}
Being honest I would avoid using strings like "STW.TOP"
. If I really had to store alignment state in the other way than just int
I would use enums which might be used in switch
in older versions of Java.
Sounds like you want a map:
// Ideally use ImmutableMap from Guava
private static final Map<String, Integer> ALIGNMENTS = mapAlignments();
private static final Map<String, Integer> mapAlignments() {
Map<String, Integer> ret = new HashMap<String, Integer>();
ret.put ("SWT.TOP", SWT.TOP);
// etc
return ret;
}
Then you can just fetch from the map (and unbox) later.
Or, better, change your method declaration to avoid this in the first place :)
Integer.parseInt(String)
can throw a NumberFormatException if the string is not specified as integer value. Also in prev versions of java, you cant apply switch-case on Strings. So better you can use the following :
if(("SWT.TOP").equals(align))
{
gd.verticalAlignment = SWT.TOP;
}