Preferred way of getting the selected item of a JComboBox

前端 未结 6 556
情歌与酒
情歌与酒 2021-01-31 16:54

HI,

Which is the correct way to get the value from a JComboBox as a String and why is it the correct way. Thanks.

String x = JComboBox.getSelectedItem().         


        
相关标签:
6条回答
  • 2021-01-31 17:09

    Note this isn't at heart a question about JComboBox, but about any collection that can include multiple types of objects. The same could be said for "How do I get a String out of a List?" or "How do I get a String out of an Object[]?"

    0 讨论(0)
  • 2021-01-31 17:16

    Don't cast unless you must. There's nothign wrong with calling toString().

    0 讨论(0)
  • 2021-01-31 17:20
    String x = JComboBox.getSelectedItem().toString();
    

    will convert any value weather it is Integer, Double, Long, Short into text on the other hand,

    String x = String.valueOf(JComboBox.getSelectedItem());
    

    will avoid null values, and convert the selected item from object to string

    0 讨论(0)
  • 2021-01-31 17:24
    JComboBox mycombo=new JComboBox(); //Creates mycombo JComboBox.
    add(mycombo); //Adds it to the jframe.
    
    mycombo.addItem("Hello Nepal");  //Adds data to the JComboBox.
    
    String s=String.valueOf(mycombo.getSelectedItem());  //Assigns "Hello Nepal" to s.
    
    System.out.println(s);  //Prints "Hello Nepal".
    
    0 讨论(0)
  • 2021-01-31 17:25

    The first method is right.

    The second method kills kittens if you attempt to do anything with x after the fact other than Object methods.

    0 讨论(0)
  • 2021-01-31 17:34

    If you have only put (non-null) String references in the JComboBox, then either way is fine.

    However, the first solution would also allow for future modifications in which you insert Integers, Doubless, LinkedLists etc. as items in the combo box.

    To be robust against null values (still without casting) you may consider a third option:

    String x = String.valueOf(JComboBox.getSelectedItem());
    
    0 讨论(0)
提交回复
热议问题