Why is jcombobox not visible?

advertisements
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Dummy{
    String newSelection = null;

    public void init(){
        JFrame jFrame = new JFrame("Something");
        jFrame.setVisible(true);
        jFrame.setSize(new Dimension(600, 600));
        jFrame.setLayout(null);
        jFrame.setBackground(Color.BLACK);

        final String[] possibleNoOfPlayers = {"Two","Three"};

        final JComboBox comboBox = new JComboBox(possibleNoOfPlayers);
        newSelection = possibleNoOfPlayers[0];
        comboBox.setPreferredSize(new Dimension(200,130));
        comboBox.setLocation(new Point(200,200));
        comboBox.setEditable(true);
        comboBox.setSelectedIndex(0);
        comboBox.setVisible(true);
        comboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                JComboBox box = (JComboBox) actionEvent.getSource();
                newSelection = (String) box.getSelectedItem();
                System.out.println(newSelection);
            }
        });
        jFrame.add(comboBox);
    }
}

I am trying to add combo box to the frame. but it is not visible. if you click the position it will show the options. but it is not visible. Please let me know if i am missing something in it.


Three things...

  1. You've called setVisible on you frame BEFORE you added it
  2. You're using null layouts
  3. You've not set a size for the comobox, which will mean it will be (effectively) rendered as 0x0 size. (ps- setPreferredSize is not doing what you think it should)...

Advisable solution...

Call setVisible last and use an appropriate layout manager