[英]GridBagLayout fix space set by weight x/y
我有一個框架,具有3個JPanels的以下布局。
----------------------------
| | |
| 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'創建的空間固定?
weightx/weighty
用於分配額外的空間。 因此實際上容器會詢問兒童的首選尺寸,如果它比可用的小,則根據重量分配額外的像素。
因此,您可以定義保存JTable
的JScrollPane
首選大小
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.