在java中如何在边框布局中嵌入网格布局
我有一个边框布局,我想在中间部分添加一个网格布局。但是,我不能先声明网格,然后再添加中心边框。我该怎么做在java中如何在边框布局中嵌入网格布局,java,swing,grid-layout,Java,Swing,Grid Layout,我有一个边框布局,我想在中间部分添加一个网格布局。但是,我不能先声明网格,然后再添加中心边框。我该怎么做 public Liability_Calculator(String s) { super(s); setSize(325,200); c = getContentPane(); c.setLayout(new BorderLayout()); //the top label total = new JLabel("
public Liability_Calculator(String s)
{
super(s);
setSize(325,200);
c = getContentPane();
c.setLayout(new BorderLayout());
//the top label
total = new JLabel("Total monthly liabilities ", JLabel.CENTER);
c.add(total, BorderLayout.NORTH);
//the grid
GridLayout grid = new GridLayout(2,2);
text_field1 = new JTextField(7);
//I GET AN ERROR HERE!!!!!!!
grid.add(text_field1);
//AND ERROR HERE!!!!!!!!!!!!!
c.add(grid, BorderLayout.CENTER);
setVisible(true);
}
您试图将组件添加到布局中,但这根本无法完成。而是使用一个JPanel,给它一个GridLayout,然后将组件添加到JPanel(这里充当“容器”)
一般来说,您会希望使用GUI的最佳布局来嵌套JPanel,其中内部JPanel使用GridLayout,外部JPanel使用BorderLayout。然后,您只需在BorderLayout.CENTER位置将内部JPanel添加到外部JPanel(此处为您的内容窗格)。提供源于气垫船答案的代码可视化: 显示类:
public class Display extends JFrame {
JPanel gridHolder = new JPanel(); // panel to store the grid
private GridLayout buttonsGrid; // space containing a buttons
private JButton myButtons[]; // grid is to be filled with these buttons
private BorderLayout mainGUILayout; // main gui layout
private Container mainGuiContainer;
public Display() {
mainGUILayout = new BorderLayout(5,5); // Border layout option
mainGuiContainer = getContentPane(); // getting content pane
mainGuiContainer.setLayout(mainFrameLayout); // setting main layout
buttonsGrid = new GridLayout(4, 1, 5, 5); // 4 buttons one over the other
myButtons = new JButton[4]; // player's hand represented with buttons
gridHolder.setLayout(buttonsGrid);
for (int x = 0; x < 4; x++) {
myButtons[x] = new JButton (" ");
gridHolder.add(myButtons[x]); }
add(gridHolder, BorderLayout.WEST);
setVisible(true); } }
public class MainGUILaunch {
public static void main (String args[]) {
Display myApplication = new Display();
myApplication.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myApplication.setSize(1024, 1024);
myApplication.setVisible(true); // displaying application }
} // End of MainGUILaunch