简体   繁体   中英

Java - How to align JPanels inside a GridLayout

This is currently what my form looks like:

在此处输入图片说明

I am trying to create a form with 4 columns of radio buttons but when I try to add the panels, holding the buttons, to the grid layout of another panel they seem to mis-align. I have not set any height of boundaries on the grid layout So I am not sure what is causing it to shift around.

My code:

public class Window extends JFrame{
public void paint(Graphics g) {
    super.paint(g); // ??
    getContentPane().setBackground(Color.WHITE); // background color
}

public static void main(String[] args) {
    Window w = new Window();
     w.setSize(1500,1000);
     w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

     JLabel title = new JLabel("Menu", SwingConstants.CENTER);
     title.setFont(title.getFont().deriveFont(32f));

     Container titlePanel = new JPanel(); // used as a container
     titlePanel.setBackground(Color.WHITE);
     FlowLayout flow = new FlowLayout(); // Create a layout manager
     titlePanel.setLayout(flow);// assign flow layout to panel
     titlePanel.add(title); // add label to panel
     w.getContentPane().add(BorderLayout.NORTH,titlePanel);

     Container mains = new JPanel(new GridLayout(7, 0));
     mains.setBackground(Color.RED);
     JLabel mainsHeader = new JLabel("Mains");
     mainsHeader.setFont(mainsHeader.getFont().deriveFont(24f));
     mains.add(mainsHeader);

     Container noodles = new JPanel(new GridLayout(4, 0));
     noodles.setBackground(Color.GREEN);
     JLabel noodlesHeader = new JLabel("Noodles");
     noodlesHeader.setFont(noodlesHeader.getFont().deriveFont(24f));
     noodles.add(noodlesHeader);

     Container sauces = new JPanel(new GridLayout(3, 0));
     sauces.setBackground(Color.BLUE);
     JLabel saucesHeader = new JLabel("Sauce");
     saucesHeader.setFont(saucesHeader.getFont().deriveFont(24f));
     sauces.add(saucesHeader);


     Container extras = new JPanel(new GridLayout(6, 0));
     extras.setBackground(Color.YELLOW);
     JLabel extrasHeader = new JLabel("Extra");
     extrasHeader.setFont(extrasHeader.getFont().deriveFont(24f));
     extras.add(extrasHeader)

     Container menuSelection = new JPanel(new GridLayout(0,4));
     menuSelection.add(mains);
     menuSelection.add(noodles);
     menuSelection.add(sauces);
     menuSelection.add(extras);

     w.getContentPane().add(menuSelection);

     w.setVisible(true);
}   
}

You don't need to set a GridLayout on every sub-panel. You should only set it on mains , possibly with correct number of rows and columns.

If you only need labels, you can add them directly to mains, and it should lay them out for you.

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