在调整大小时,gridbaglayout的组件是否可以填充父框架?

时间:2014-07-13 15:00:53

标签: java swing resize layout-manager gridbaglayout

我有一个JFrame,其JPanel根据GridBagLayout进行了实例化。在运行时,面板使用基于某些描述的组件填充,宽度,高度和x,y坐标在说明中给出,以与gridwidthgridheight,{{1}一起使用gridx中的{}和gridy字段。组件本身也可以是GridBagConstraints个子组件和JPanel,GUI在树中描述,因此Frame是递归填充的。

我遇到的问题是,当调整框架大小时,内部组件不会被拉伸以填充其给定的宽度和高度。我已经通过屏幕截图给出了下面布局代码的示例。

GridBagConstraints

When running it After stretching

我需要它,因此在图2中,保持组件的内部import javax.swing.*; import javax.swing.border.TitledBorder; import java.awt.*; import java.util.*; public class GridBagTest extends JPanel { private final GridBagConstraints gbc = new GridBagConstraints(); public GridBagTest(){ setLayout(new GridBagLayout()); add(gbcComponent(0,0,1,2), gbc); add(gbcComponent(1,0,2,1), gbc); add(gbcComponent(1,1,1,1), gbc); add(gbcComponent(2,1,1,1), gbc); } //Returns a JPanel with some component inside it, and sets the GBC fields private JPanel gbcComponent(int x, int y, int w, int h){ gbc.gridx = x; gbc.gridy = y; gbc.gridwidth = w; gbc.gridheight = h; gbc.fill = GridBagConstraints.BOTH; JPanel panel = new JPanel(); JTextField text = new JTextField("(" + w + ", " + h + ")"); panel.setBorder(new TitledBorder("(" + x + ", " + y + ")")); panel.add(text); return panel; } public static void main (String args[]){ JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setContentPane(new GridBagTest()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } 被调整大小以填充JPanel上各自的宽度和高度,理想情况下也可以拉伸它们的组件。

2 个答案:

答案 0 :(得分:12)

这通常是由于你没有设置weightx和重量限制。

尝试:

gbc.gridx = x; 
gbc.gridy = y;
gbc.gridwidth = w;
gbc.gridheight = h;

// **** add here:
gbc.weightx = 1.0;
gbc.weighty = 1.0;

如果需要,这将允许您的GUI在x和y方向上扩展。

答案 1 :(得分:0)

您可以在调整JPanel大小时设置columnWidthsrowHeights。 看看这个样本。我为两列案例修改了代码:

public GridBagTest(){

    setLayout(new GridBagLayout());
    add(gbcComponent(0,0,1,2), gbc);    
    add(gbcComponent(1,0,1,1), gbc);

    addComponentListener(new java.awt.event.ComponentAdapter() {
        @Override
        public void componentResized(java.awt.event.ComponentEvent evt) {
            GridBagLayout layout = (GridBagLayout) getLayout();
            JPanel panel = (JPanel)evt.getComponent();
            int width = panel.getWidth();
            int height = panel.getHeight();
            int wGap = panel.getInsets().left+panel.getInsets().right;
            int hGap = panel.getInsets().top+panel.getInsets().bottom;
            layout.columnWidths = new int[]{width/2-wGap, width/2-wGap};
            layout.rowHeights = new int[]{height-hGap};
        }
    });

}

根据您的列数和行数,您可以更改它。结果如下: enter image description here enter image description here