2016-01-22 60 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