获取 JComboBox 所选项目的首选方式 [英] Preferred way of getting the selected item of a JComboBox

查看:37
本文介绍了获取 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.

然而,第一个解决方案还允许您在未来的修改中插入 Integers、Doubless、LinkedLists 等,如组合框中的项目.

However, the first solution would also allow for future modifications in which you insert Integers, Doubless, LinkedLists 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆