How to add jpanel to a specific cell of GridLayout

2019-09-20 11:52发布

问题:

in the below code, i created a GridLayot with 3 rows and 3 columns, what i want to do is,,to add jpanel_1 into a specifc cell of the Gridlayout, lets say in the grid cell number (2,3).

Code:

private void setUpGUI2() {
    // TODO Auto-generated method stub
    jFrame_2 = new JFrame("Border Demo");
    GridLayout gridLayOut = new GridLayout(3,3);
    jFrame_2.setLayout(gridLayOut);

    jPanel_1 = new JPanel(new BorderLayout());
    jPanel_2 = new JPanel(new BorderLayout());

    jPanel_1.setBorder(BorderFactory.createTitledBorder("title"));
    //jPanel_1.setBounds(30, 100, 110, 300);
    jPanel_1.add(jLabel_Hello, BorderLayout.EAST);

    jPanel_2.setBorder(BorderFactory.createLoweredBevelBorder());
    //jPanel_2.setBounds(20, 50, 120, 80);
    jPanel_2.add(jLabel_Hello, BorderLayout.SOUTH);

    //jFrame_2.setBounds(0, 0, 600, 600);
    jFrame_2.add(jPanel_1);//how to add jpanel_1 to a specific cell of Gridlayout defined above
    //jPanel_1.add(jPanel_2);
    jFrame_2.add(jPanel_2);
    jFrame_2.pack();
    jFrame_2.setVisible(true);
}

回答1:

I think there is no chance. You need to add them one by one. frame.add(...); frame.add(...);
I don't clearly understand what you want as result, but using GridLayout(3, 3) with only 2 panels is the same as use GridLayout(0, 2).
P.S. Check out GridBagLayout - it can be more useful for you.



回答2:

Depending on what you want to do, you could add "dummy" components (like a JLabel) to the cells you don't want to use. If I recall correctly, GridLayout will layout in col/row order

So of you wanted to add a component to the second column on the second row, you would have to add four JLabel's first, do pad out the layout