获取 JComboBox 所选项目的首选方式 [英] Preferred way of getting the selected item of a JComboBox
本文介绍了获取 JComboBox 所选项目的首选方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从 JComboBox 作为字符串获取值的正确方法是什么,为什么是正确的方法.谢谢.
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().toString();
或
String x = (String)JComboBox.getSelectedItem();
推荐答案
如果您只在 JComboBox 中放置了(非空)String
引用,那么两种方法都可以.
If you have only put (non-null) String
references in the JComboBox, then either way is fine.
然而,第一个解决方案还允许您在未来的修改中插入 Integer
s、Doubles
s、LinkedList
s 等,如组合框中的项目.
However, the first solution would also allow for future modifications in which you insert Integer
s, Doubles
s, LinkedList
s etc. as items in the combo box.
要对 null
值保持稳健(仍然没有强制转换),您可以考虑第三种选择:
To be robust against null
values (still without casting) you may consider a third option:
String x = String.valueOf(JComboBox.getSelectedItem());
这篇关于获取 JComboBox 所选项目的首选方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文