Search code examples
javaswinginstancejcombobox

Instance of JComboBox


Well i have a problems when a instance the Jcombox is not a problem of code( i think) it just that when a instance the JCombox, the buttons a i create are not visible in my Window until y resize the windows, and the they appear

public class ventana extends JFrame {

        static JCheckBox ch1;
    static JCheckBox ch2;
    static JCheckBox ch3;
    static ButtonGroup bg;
    static JComboBox cb;
public static void main(String[] args) {

    JFrame jf = new JFrame("asd");
    jf.setVisible(true);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.setSize(200,320);
    jf.setLayout(new FlowLayout(FlowLayout.CENTER));
    ch1 = new JCheckBox();
    ch2 = new JCheckBox();
    ch3 = new JCheckBox();
    String [] x= {"1","2","3"};
    cb = new JComboBox(x);
    cb.addItem("Asdd");
    cb.addActionListener(e ->{

    });
    bg = new ButtonGroup();
    bg.add(ch1);
    bg.add(ch2);
    bg.add(ch3);

    jf.add(ch1);
    jf.add(ch2);
    jf.add(ch3);
    jf.add(cb);


}

}

Note: I try with JPanel too and is the same problem, and with repaint() too!

Note: the app doesnt have any fuctionality, i just wanna know how to resolve the problem

UPDATE: to resolve the problem you only have to put the "jf.setVisible(true);" at the end.


Solution

  • Set your JFrame to visible after you add all of your components.

    This is because you are adding your components AFTER your JFrame painted to the screen (by setting visible to true) so if you set visible to true after you add the components it will paint with the components you added.

    The reason it would only paint after you re-sized the window is because resizing the window causes it to paint again (and as @camickr mentioned in the comments, causes the layout manager to invoke and position the elements since you are not giving them a size).

    If you want to repaint your JFrame after you set it to visible you can also use jf.revalidate() followed by jf.repaint().

    Code:

     JFrame jf = new JFrame("asd");
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.setSize(200,320);
    jf.setLayout(new FlowLayout(FlowLayout.CENTER));
    ch1 = new JCheckBox();
    ch2 = new JCheckBox();
    ch3 = new JCheckBox();
    String [] x= {"1","2","3"};
    cb = new JComboBox(x);
    cb.addItem("Asdd");
    cb.addActionListener(e ->{
    
    });
    bg = new ButtonGroup();
    bg.add(ch1);
    bg.add(ch2);
    bg.add(ch3);
    
    jf.add(ch1);
    jf.add(ch2);
    jf.add(ch3);
    jf.add(cb);
    jf.setVisible(true); //This is where you want to set your JFrame to visible