简体   繁体   中英

Java - GridLayout resize JPanel

I'm trying to resize the height of each JPanel inside another JPanel which has a GridLayout.

This is what I have so far:

JPanel store = new JPanel();
store.setLayout(new GridLayout(4, 0));

JPanel computerPanel = new JPanel();
computerPanel.setBorder(BorderFactory.createTitledBorder("Computers"));
computerPanel.setPreferredSize(new Dimension(20, 30));

JPanel cablesPanel = new JPanel();
cablesPanel.setBorder(BorderFactory.createTitledBorder("Cables"));

JPanel accessoriesPanel = new JPanel();
accessoriesPanel.setBorder(BorderFactory.createTitledBorder("Accessories"));

JPanel repairPanel = new JPanel();
repairPanel.setBorder(BorderFactory.createTitledBorder("Repair"));

store.add(computerPanel);
store.add(cablesPanel);
store.add(accessoriesPanel);
store.add(repairPanel);

JPanel view = new JPanel();
view.setLayout(new BorderLayout());
view.add(store, BorderLayout.CENTER);

add(view);

This is what the GUI outputs: 屏幕截图

I want to resize each JPanel (computerPanel, cablelPanel, accessoriesPanel, repairPanel) inside the JPanel store.

I have tried:

computerPanel.setPrefferedSize() but that doesn't work...

If you want to be able to resize each JPanel, you're not using the appropriate LayoutManager. GridLayout (which you're using now) specifically does not allow such resizing, instead fixing each cell to the exact same size.

Consider using a different LayoutManager, such as BoxLayout or GridBagLayout.

See here to figure out which LayoutManager is most appropriate for your needs.

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