Java - How to set String as static int

后端 未结 4 549
予麋鹿
予麋鹿 2021-01-28 08:24

I have a method that accepts only a String.

public void setVerticalAlignment(String align) {
            ...
    gd.verticalAlignment = align;   // accepts only          


        
相关标签:
4条回答
  • 2021-01-28 08:51

    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.

    0 讨论(0)
  • 2021-01-28 08:53

    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.

    0 讨论(0)
  • 2021-01-28 09:06

    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 :)

    0 讨论(0)
  • 2021-01-28 09:07
    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;
    }
    
    0 讨论(0)
提交回复
热议问题