Java - How to set String as static int

后端 未结 4 589
予麋鹿
予麋鹿 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.

提交回复
热议问题