adn*_*252 8 java swing resize layout-manager gridbaglayout
我有一个用JFrameroot JPanel实例化的根GridBagLayout.在运行时,面板被填充有基于某些描述的部件,并且宽度,高度以及x,y COORDS中给出的描述中,以与被使用gridwidth,gridheight,gridx和gridy在字段GridBagConstraints.组件本身也可以JPanel是带有自己子组件的组件GridBagConstraints,GUI在树中描述,因此Frame是递归填充的.
我遇到的问题是,当调整框架大小时,内部组件不会被拉伸以填充其给定的宽度和高度.我已经给出了下面的布局代码示例,并附有截图.
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);
}
}
Run Code Online (Sandbox Code Playgroud)

我需要它,所以在图2中,JPanel保持组件的内部尺寸被调整大小以填充它们各自的宽度和高度GridBagLayout,理想地也拉伸它们的组件.
Hov*_*els 14
这通常是由于您没有设置weightx和重量限制.
尝试:
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = w;
gbc.gridheight = h;
// **** add here:
gbc.weightx = 1.0;
gbc.weighty = 1.0;
Run Code Online (Sandbox Code Playgroud)
如果需要,这将允许您的GUI在x和y方向上扩展.