0

when i used the method setSelectedItem(null) it brings me null when i want to get the value from the jcomboBox no matter if pressed something else... this is my code:

import javax.swing.JComboBox;
import javax.swing.JFrame;

public class ddd extends JFrame{

final static String[] arr= {"A","B"};

public ddd()
{
    super("exp");
    setSize(300,200);
    JComboBox<String> cb=new JComboBox<String>(arr);
    add(cb);
    cb.setSelectedItem(null);
    String s=(String)cb.getSelectedItem();
    System.out.println(s);
    setVisible(true);
}
public static void main(String[] args) {
    // TODO Auto-generated method stub

    new ddd();

}

}
camickr
  • 321,443
  • 19
  • 166
  • 288
Ruthie
  • 11
  • 1
  • 1
    You need to use a listener to react to selection events; that's why you're not seeing any change in value. As soon as the combo box is added, you attempt to receive the selection. See [this post](https://stackoverflow.com/questions/58939/jcombobox-selection-change-listener) for reacting to events from your combo box. – Vince Jun 09 '20 at 17:30
  • There is a similar question. This is the answer : https://stackoverflow.com/a/11999607/13695921 – EEAH Jun 09 '20 at 17:48
  • 1
    Of course it returns null because nothing is selected. Read the section from the Swing tutorial on [How to use Combo Boxes](https://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html). I suggest you read other sections from the tutorial to learn some Swing basics. You can't code if you don't understand the basics of event driven programing, which means you need to use listeners to respond to user events. – camickr Jun 09 '20 at 17:50
  • I really wish people would put some thought into closing a question as a duplicate. That link does nothing different that the code the OP has posted here. The answer there does absolutely nothing to solve the OP's problem. The problem is "when" the code is executed and the concept of understanding event driven programming. – camickr Jun 10 '20 at 02:00

0 Answers0