我想在GridBagLayout中的JPanels中嵌套JPanels。这是我遇到的问题的图片:
您可以说,在GridBagLayout中的JPanel中嵌套组件会导致JPanel的大小膨胀。这是一个问题,因为我不能在不更改组件大小的情况下将组件添加到JPanels。
代码如下:
package gui;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GridBagDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Grid grid = new Grid();
JFrame frame = new JFrame();
frame.setBounds(100,100, 500, 500);
frame.add(grid);
frame.setVisible(true);
}
}
class Grid extends JPanel {
public Grid () {
setBackground(Color.white);
GridBagLayout bagLayout = new GridBagLayout();
setLayout(bagLayout);
GridBagConstraints gc = new GridBagConstraints();
JPanel navBar = new JPanel();
navBar.setBackground(Color.GREEN);
JLabel label = new JLabel("hello world");
navBar.add(label);
gc.fill = GridBagConstraints.BOTH;
gc.gridx = 0;
gc.gridy = 0;
gc.gridwidth = 2;
gc.weightx = 0.1;
gc.weighty = 0.05;
add(navBar, gc);
JPanel toolBar = new JPanel();
toolBar.setBackground(Color.blue);
gc.fill = GridBagConstraints.BOTH;
gc.gridx = 0;
gc.gridy = 1;
gc.gridwidth = 1;
gc.weightx = 0.3;
gc.weighty = 0.3;
add(toolBar, gc);
//Second row
JPanel content = new JPanel();
content.setBackground(Color.CYAN);
gc.fill = GridBagConstraints.BOTH;
gc.gridx = 0;
gc.gridy = 1;
gc.weightx = 0.15;
gc.weighty = 0.3;
add(content, gc);
JPanel navBarChild = new JPanel();
navBarChild.setBackground(Color.MAGENTA);
gc.fill = GridBagConstraints.BOTH;
gc.gridx = 1;
gc.gridy = 1;
gc.weightx = 0.3;
gc.weighty = 0.3;
add(navBarChild, gc);
//Third row
JPanel bottomLeft = new JPanel();
bottomLeft.setBackground(Color.DARK_GRAY);
gc.fill = GridBagConstraints.BOTH;
gc.gridx = 0;
gc.gridy = 2;
gc.weightx = 0.1;
gc.weighty = 0.3;
add(bottomLeft, gc);
JPanel bottomRight = new JPanel();
bottomRight.setBackground(Color.LIGHT_GRAY);
gc.fill = GridBagConstraints.BOTH;
gc.gridx = 1;
gc.gridy = 2;
gc.weightx = 0.3;
gc.weighty = 0.3;
add(bottomRight, gc);
}
}
我的首选行为是在不增加JPanel大小的情况下将组件添加到嵌套JPanel的能力。
我已经在Google上研究了这个主题一段时间,大多数结果与我的问题无关。有两个SO答案有些相关,但实际上不是同一问题。