如何在JDialog中动态添加组件?

时间:2016-08-23 11:54:27

标签: java swing jcombobox jdialog

我正在尝试创建第一张图片中给出的GUI,但我无法做到。here is the image 我只得到一个combo1,combo2,combo3和serialNoLabel而不是5 [5是列表的大小]

    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();
    }

1 个答案:

答案 0 :(得分:3)

我认为这是一个布局问题,导致你的masterPanels彼此重叠。

所以我会做这样的事情:

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]);
    }

当然你也可以使用其他布局。但我相信你想要FlowLayout。请参阅有关FlowLayout here

的文档

您可以详细了解其他布局here