Preferred way of getting the selected item of a JComboBox

前端 未结 6 608
情歌与酒
情歌与酒 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: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".
    

提交回复
热议问题