2016-01-22 88 views
3

我正在爲聊天程序編寫GUI。我似乎無法讓scroller水平和垂直填充框架,並且messageInput水平填充框架。這是它的外觀:Java GridBagLayout不會水平填充框架

enter image description here

import javax.swing.*; 
import java.awt.*; 

public class GUI extends JFrame{ 

private JPanel panel; 
private JEditorPane content; 
private JTextField messageInput; 
private JScrollPane scroller; 
private JMenu options; 
private JMenuBar mb; 
private JMenuItem item; 

public GUI(){ 
    /** This is the frame**/ 
    this.setPreferredSize(new Dimension(380,600)); 
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    panel = new JPanel(); 
    panel.setLayout(new GridBagLayout()); 
    GridBagConstraints c = new GridBagConstraints(); 
    c.fill = GridBagConstraints.HORIZONTAL; 

    /** This is where the context shows up **/ 
    content = new JEditorPane(); 
    content.setEditable(false); 

    /** Scroller that shows up in the context JEditorPane **/ 
    scroller = new JScrollPane(content); 
    c.weightx = 0.0; 
    c.weighty = 0.0; 
    c.gridx = 0; 
    c.gridy = 0; 
    panel.add(scroller, c); 

    /** This is where you type your message **/ 
    messageInput = new JTextField(); 
    c.weightx = 0.0; 
    c.weighty = 0.0; 
    c.gridx = 0; 
    c.gridy = 1; 
    c.weighty = 0.5; 
    panel.add(messageInput, c); 

    mb = new JMenuBar(); 
    options = new JMenu("Options"); 
    mb.add(options); 
    this.setJMenuBar(mb); 

    this.add(panel); 
    this.pack(); 
    this.setVisible(true); 

} 



public static void main(String[] args) { 
    new GUI(); 
} 
} 
+1

只要權重爲零,它將永遠不會填滿單元格。重點在於告訴GridBagLayout多少額外的空間應該被賦予該單元格的內容。 – VGR

回答

5

得到scroller水平和垂直填充框架和messageInput水平方向上填滿幀。

你要填寫的兩個方向,所以設置

c.fill = GridBagConstraints.BOTH; // not HORIZONTAL 

接下來的部分是固定的權重,這將告訴多大的空間分配給每個組件(相對):

scroller = new JScrollPane(content); 
    c.weightx = 0.5; 
    c.weighty = 1.0; 
    c.gridx = 0; 
    c.gridy = 0; 
    panel.add(scroller, c); 

    messageInput = new JTextField(); 
    c.weightx = 0.5; 
    c.weighty = 0.0; 
    c.gridx = 0; 
    c.gridy = 1; 
    panel.add(messageInput, c); 

weightx應該是一個非零值,以允許組件水平拉伸。 weighty對於編輯器應該不爲零,但對於文本字段不應該佔用額外的垂直空間(在這種情況下,您無需爲其設置c.fill = GridBagConstraints.HORIZONTAL)。

enter image description here