简体   繁体   中英

How to put two java swing JPanels next to each other and have a table in it?

I am trying to build my own "Battleship" game and have problems with swing. I now read endless docs on oracle tutorials on LayoutManagers, but not any of them works as I understand them. They only add a few buttons, but never two individual panels.

        JPanel Background = new JPanel();
    Background.setLayout(new BoxLayout(Background, BoxLayout.X_AXIS));
    panelPlayer = new JPanel();
    panelPlayer.setBorder(BorderFactory.createLineBorder(Color.black));
    panelPlayer.setSize(700, 600);
    // PC Field
    panelPc = new JPanel();
    panelPc.setBorder(BorderFactory.createLineBorder(Color.black));
    panelPc.setSize(700, 600);
    //adding to frame
    getContentPane().add(Background);
    Background.add(panelPlayer);
    Background.add(panelPc);

After that I have a loop thats adds 16x16 buttons in a JButton[] once for every panel.

How to get the two panels to show a table layout? I used GridLayout before, the grid works, but it always takes up the whole space of the frame, not of the Container or Panel or else. The panels are overlapping then. GridBagLayout just puts the buttons in a row and beyond the screen.

Don't fix the size of the panel while using any layout. It works only when you use null layout

You can achieve your goal with GridBagLayout . While adding buttons specify gridx , gridy correctly, it will add buttons like table

just keep nesting the layouts.

in your case make a big one with two sides - then in each side place another panel with your grid.

You can solve this by nesting panels. Each panel has its own layout manager, so it is a matter of breaking up your UI into pieces and choosing the layout manager for each piece.

If you want two panels side-by-side, then the panel that contains them should have a FlowLayout manager with horizontal orientation. Create a panel with FlowLayout and add the panels to it.

If each of the the side-by-side panels needs the grid of buttons, then set the panel layout to GridLayout and put the buttons in the panel. This fits what I remember of Battleship; in a grid layout, all the grid elements remain the same size no matter how the window is resized.

That should get you started. If, as I expect, you will want another panel with some game controls on it, look into BorderLayout; it has a section on each edge of a rectangle and another in the middle. Put the panel containing the two grids in the center of a panel using BorderLayout, and then your game controls can go in a panel to the north, south, east, or west of that.

Good luck. Let us know if you have a specific problem (in another question).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM