Search code examples
javaswingjcomboboxjdialog

How can be components added dynamically in the JDialog?


I am trying to create GUI like given in first picture, but I am not able to do it.here is the image I am getting only one combo1, combo2, combo3 and serialNoLabel instead of 5 [5 is the size of list]

    ArrayList<String> list; // the size of the list is 5
    JComboBox combo1[] = new JComboBox[list.size()];
    JComboBox combo2[] = new JComboBox[list.size()];
    JComboBox combo3[] = new JComboBox[list.size()];
    JLabel SerialNoLabel[] = new JLabel[list.size()];
    JPanel masterPanel[] = new JPanel[list.size()];

    JDialog masterDialog =  new JDialog();
    masterDialog.setVisible(true);
    masterDialog.setSize(800, 500);
    masterDialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    masterDialog.setVisible(true);
    for(int j =0; j < list.size(); j++) {
        masterPanel[j] = new JPanel();
        SerialNoLabel[j] = new JLabel(list.get(j));
        masterPanel[j].add(SerialNoLabel[j]);
        combo1[j] = new JComboBox();
        masterPanel[j].add(combo1[j]);
        combo2[j] = new JComboBox();
        masterPanel[j].add(combo2[j]);
        combo3[j] = new JComboBox();
        masterPanel[j].add(combo3[j]);
        masterDialog.add(masterPanel[j]);
        masterDialog.revalidate();
    }

Solution

  • I believe it's a layout issue leading your masterPanels to be on top of each other.

    So I would do something like this:

    JPanel mainPanel = new JPanel();
    FlowLayout experimentLayout = new FlowLayout();
    mainPanel.setLayout(experimentLayout);
    for(int j =0; j < list.size(); j++) {
            masterPanel[j] = new JPanel();
            SerialNoLabel[j] = new JLabel(list.get(j));
            masterPanel[j].add(SerialNoLabel[j]);
            combo1[j] = new JComboBox();
            masterPanel[j].add(combo1[j]);
            combo2[j] = new JComboBox();
            masterPanel[j].add(combo2[j]);
            combo3[j] = new JComboBox();
            mainPanel.add(masterPanel[j]);
        }
    

    Of course you could other layouts as well. But I believe you want to go for a FlowLayout. See the documentation about FlowLayout here.

    You can learn more about other layouts here