Preferred way of getting the selected item of a JComboBox

前端 未结 6 558
情歌与酒
情歌与酒 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: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());
    

提交回复
热议问题