2017-01-14 82 views
0

我想達到的目標是這樣的:如何使GridBagLayout在Java中的網格不同?

enter image description here

這是我的代碼:

JDialog messageDialog = new JDialog(); 
messageDialog.setLayout(new GridBagLayout()); 
GridBagConstraints c = new GridBagConstraints(); 
messageDialog.setBounds(0, 0, 350, 250); 
messageDialog.setLocationRelativeTo(null); 
messageDialog.setVisible(true); 

JPanel btnPanel = new JPanel(); 
JPanel clearPanel = new JPanel(); 
JPanel labelsPanel = new JPanel(); 
JPanel txtPanel = new JPanel(); 
JButton newMessage = new JButton("New"); 
JButton recievedMessages = new JButton("Recieved"); 
JButton sendMessages = new JButton("Sent"); 
JButton refreshMessages = new JButton("Refresh"); 
JLabel recievedMessLab = new JLabel("Messages get:"); 
JTextPane txtToSend = new JTextPane(); 

btnPanel.setLayout(new GridLayout(4, 1)); 
btnPanel.add(newMessage); 
btnPanel.add(recievedMessages); 
btnPanel.add(sendMessages); 
btnPanel.add(refreshMessages); 

c.gridx = 0; 
c.gridy = 0; 
messageDialog.add(clearPanel, c); 

c.gridx = 1; 
c.gridy = 0; 
messageDialog.add(labelsPanel, c); 

c.gridx = 0; 
c.gridy = 1; 
messageDialog.add(btnPanel, c); 

c.gridx = 1; 
c.gridy = 1; 
messageDialog.add(txtPanel, c); 

labelsPanel.add(recievedMessLab); 

我不知道爲什麼我避開所有的面板和我一些自由空間無法弄清楚如何調整網格大小。 Oracle教程也沒有幫助。調整這個最簡單的方法是什麼?如何擺脫這個自由空間?

回答

1

您需要添加重量填寫信息到您的GridBagConstraints所以佈局管理器知道要STRETCH時在可用空間的組件。

嘗試以下操作:

c.gridx = 0; 
c.gridy = 0; 
c.fill = c.NONE; // dont fill (strech) 
messageDialog.add(clearPanel, c); 

c.gridx = 1; 
c.gridy = 0; 
c.weightx = 1; // horizontal weight: 1 
c.fill = c.HORIZONTAL; // fill (strech) horizontally 
messageDialog.add(labelsPanel, c); 

c.gridx = 0; 
c.gridy = 1; 
c.weightx = 0; // horizontal weight: back to 0 
c.weighty = 1; // vertical weight: 1 
c.fill = c.VERTICAL; // fill (strech) vertically 
messageDialog.add(btnPanel, c); 

c.gridx = 1; 
c.gridy = 1; 
c.weightx = 1; // both weights: 1 
c.weighty = 1; // both weights: 1 
c.fill = c.BOTH; // and fill both ways, vertically and horizontally 
messageDialog.add(txtPanel, c); 

教程再講約weightxweightyfill的一部分,得到一條線索,他們是如何工作的。

PS:txtPanel爲空並且txtToSend從不使用?