java JComboBox 到字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12756388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:05:06  来源:igfitidea点击:

JComboBox to string

javaswingcomboboxjcombobox

提问by gabrielle fregil

I have a String array of names, and then I added it into an editable JComboBox.

我有一个字符串名称数组,然后我将它添加到一个可编辑的 JComboBox 中。

The user can either pick his/her name from the choices or just input his/her name if not in the choices.

用户可以从选项中选择他/她的名字,或者如果不在选项中,则只输入他/她的名字。

How do I put the user input into a new string variable?

如何将用户输入放入新的字符串变量中?

   String [] chooseName = { Mark, John, Allison, Jessica };
   JComboBox combo = new JComboBox (chooseName);
   combo.setEditable(true);

   String chosenName =  /*  how do i place what the user inputed here? */

回答by Drose

I would add an action listener to the combo box. By doing it in the same block there, it will simply grab the default (I believe). This way we make sure we grab the value once selected.

我会向组合框添加一个动作侦听器。通过在同一个块中执行它,它会简单地获取默认值(我相信)。这样我们就可以确保我们在选择后获取值。

String [] chooseName = { Mark, John, Allison, Jessica };
final JComboBox combo = new JComboBox (chooseName);
combo.setEditable(true);
combo.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String chosenName =  (String) combo.getSelectedItem();
    }
});

回答by davidXYZ

You can use:

您可以使用:

combo.getSelectedItem()

combo.getSelectedItem()

回答by MGR

This will Help You..

这将帮助你..

combo.getSelectedItem();

For More reference follow this link, it will help you..

如需更多参考,请点击此链接,它将帮助您..

http://www.roseindia.net/java/example/java/swing/ComboBox.shtml

http://www.roseindia.net/java/example/java/swing/ComboBox.shtml