日期:2014-05-20  浏览次数:20631 次

Swing GridBagLayout 布局的问题
窗体需要分布三部分,左、中、右,而且随着窗体缩放的时候 ,中间部分保持不变,左、右同比例变化 ,于是使用了 GridBagLayout 
Java code

    GridBagLayout gbl_centerPanel = new GridBagLayout();
        gbl_centerPanel.columnWidths = new int[]
        { 3, 1, 3 };
        gbl_centerPanel.rowHeights = new int[]
        { 1 };
        gbl_centerPanel.columnWeights = new double[]
        { 1.0, 0, 1.0 };
        gbl_centerPanel.rowWeights = new double[]
        { 1.0 };
        centerPanel.setLayout(gbl_centerPanel);


窗体的设计界面如下:

但是运行界面就不正确了 ,如下:

而且,窗体缩放时,左、右两侧也不是同比例缩放。

------解决方案--------------------
给你个TableLayout的例子,功能是你要求的,可以看出TableLayout很简单
Java code
double[][] size = {
    {0.5, TableLayout.PREFERRED, 0.5},
    {TableLayout.FILL}
};
Container container = frame.getContentPane();
container .setLayout(new TableLayout(size));
container .add(new LeftPanel(), "0, 0");
container .add(new CenterPanel(), "1, 0");
container .add(new RightPanel(), "2, 0");

------解决方案--------------------
import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Calculator extends JFrame

{
private JTextField displayField;// 计算结果显示区

private String lastCommand;// 保存+,-,*,/,=命令

private double result;// 保存计算结果

private boolean start;// 判断是否为数字的开始



private Container container;
private GridBagLayout layout;
private GridBagConstraints constraints;
public Calculator()
{
super("java_刘阳");
container = getContentPane();
layout = new GridBagLayout();
container.setLayout(layout);
constraints = new GridBagConstraints();

start = true;
result = 0;
lastCommand = "=";
displayField = new JTextField(20);
displayField.setHorizontalAlignment(JTextField.RIGHT);

//注意这里
constraints.gridx =0;
constraints.gridy =0;
constraints.gridwidth = 3; //在第几格显示
constraints.gridheight = 1;
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 100; //调整比例
constraints.weighty = 100;
layout.setConstraints(displayField, constraints);
container.add(displayField);



ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();



addButton("Backspace", 0, 1, 2, 1, insert);

addButton("CE", 2, 1, 1, 1, insert);

addButton("C", 3, 1, 1, 1, insert);

addButton("7", 0, 2, 1, 1, insert);

addButton("8", 1, 2, 1, 1, insert);

addButton("9", 2, 2, 1, 1, insert);

addButton("/", 3, 2, 1, 1, command);
//
// addButton("4", 0, 3, 1, 1, insert);
//
// addButton("5", 1, 3, 1, 1, insert);
//
// addButton("6", 2, 3, 1, 1, insert);

// addButton("*", 3, 3, 1, 1, command);
//
// addButton("1", 0, 4, 1, 1, insert);
//
// addButton("2", 1, 4, 1, 1, insert);
//
// addButton("3", 2, 4, 1, 1, insert);
//
// addButton("-", 3, 4, 1, 1, command);
//
// addButton("0", 0, 5, 1, 1, insert);
//
// addButton("+/-", 1, 5, 1, 1, insert);// 只显示"-"号,"+"没有实用价值
//
// addButton(".", 2, 5, 1, 1, insert);