我的框架具有3个JPanel的以下布局。
----------------------------
| | |
| l | |
| e | //toppanel |
| f | |
| t |----------------------|
| p | |
| n | //bottompanel |
| l | |
| | |
----------------------------
我使用GridBagLayout
这是该布局的代码
public class UITests extends JFrame{
public UITests(){
setLayout(new GridBagLayout());
//the three main panels
JPanel leftPanel = new JPanel();
JPanel topPanel = new JPanel();
JPanel bottomPanel = new JPanel();
leftPanel.setBackground(Color.YELLOW);
topPanel.setBackground(Color.GREEN);
bottomPanel.setBackground(Color.PINK);
//position the three main panels
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = 2;
gbc.gridwidth = 1;
gbc.fill = gbc.BOTH;
gbc.weightx = .2;
gbc.weighty = 1;
getContentPane().add(leftPanel, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.fill = gbc.BOTH;
gbc.weightx = .8;
gbc.weighty = .5;
getContentPane().add(topPanel, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.fill = gbc.BOTH;
gbc.weightx = .8;
gbc.weighty = .5;
getContentPane().add(bottomPanel, gbc);
setSize(600,600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new UITests();
}
}
问题是,当我在顶部面板中添加JTable
时,底部面板的高度会缩小,就像顶部面板的一些高度一样。以下是顶部面板中表格的代码,在设置三个主要面板的背景后添加。
Object[][] contents = {{"haha","hehe", "hihi", "hoho", "huhu"},
{"haha","hehe", "hihi", "hoho", "huhu"},
{"haha","hehe", "hihi", "hoho", "huhu"},
{"haha","hehe", "hihi", "hoho", "huhu"}};
Object[] heads = {"Haha Head", "Hehe Head", "Hihi Head", "Hoho Head", "Huhu Head"};
JTable table = new JTable(contents, heads);
JScrollPane scrollTable = new JScrollPane(table);
//add components to topPanel
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = gbc.BOTH;
topPanel.setLayout(new GridBagLayout());
topPanel.add(scrollTable, gbc);
框架现在看起来像
----------------------------
| | |
| l | |
| e | //toppanel |
| f | //new table created |
| t | |
| p | |
| n | |
| l |----------------------|
| | //bottompanel |
----------------------------
那么,如何使'weightx'或'weighty'创建的空间固定?
答案 0 :(得分:2)
weightx/weighty
用于分配额外空间。所以实际上容器要求孩子们选择他们喜欢的尺寸,如果它比可用的小,那么根据重量分配额外的像素。
因此,您可以定义包含JScrollPane
JTable
的首选大小