【发布时间】:2017-07-18 19:19:14
【问题描述】:
我想用GridBagLayout来实现这个效果:
|-----------|
| Button1 |
|-----------|
|-----------|
| Button2 |
|-----------|
我最初只是放置了按钮,但 GridBagLayout 忽略了空单元格。现在,我正在尝试使用 Box.createHorizontalStrut(10) 作为间隔,但 GridBagLayout 正在拉伸空间以给我一个 2x2 网格。我也试过 JLabels 和 JPanels 作为间隔,但我仍然得到一个 2x2 网格。这是我的代码:
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutDemo extends JFrame
{
// class level references
GridBagLayout layout;
JButton button1, button2;
// constructor
public GridBagLayoutDemo()
{
super("GridBagLayout Demo");
layout = new GridBagLayout();
setLayout( layout );
// create components
button1 = new JButton("Button 1");
button2 = new JButton("Button 2");
// components should be resized vertically AND horizontally (BOTH) to fill given area
int fill = GridBagConstraints.BOTH;
// if you do not fill the area, where should the component go?
int anchor = GridBagConstraints.CENTER;
// place components on the frame using a method
placeComponent( button1, 0, 0, 2, 2, 0.5, 0.5, fill, 0, 0, 0, 0, anchor );
placeComponent( Box.createHorizontalStrut(5), 2, 0, 1, 2, 0.5, 0.5, fill, 0, 0, 0, 0, anchor );
placeComponent( Box.createHorizontalStrut(5), 0, 2, 1, 2, 0.5, 0.5, fill, 0, 0, 0, 0, anchor );
placeComponent( button2, 1, 2, 2, 2, 0.5, 0.5, fill, 0, 0, 0, 0, anchor );
}
/// Place the component on the GridBag with appropriate parameters
private void placeComponent( Component comp, int column, int row, int width, int height, double weightX, double weightY,
int fill, int marginTop, int marginLeft, int marginBottom, int marginRight, int anchor )
{
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = column; // column to start
constraints.gridy = row; // row to start
constraints.gridwidth = width; // number of cells wide
constraints.gridheight = height; // number of cells tall
constraints.weightx = weightX; // when size is changed, grow in x direction
constraints.weighty = weightY; // when size is changed, grow in y direction
constraints.fill = fill; // should the component fill the given area? GridBagConstraints.NONE, GridBagConstraints.BOTH, GridBagConstraints.CENTER, etc
constraints.insets = new Insets( marginTop, marginLeft, marginBottom, marginRight );
constraints.anchor = anchor;
layout.setConstraints(comp, constraints);
add(comp); // place component on the frame with these parameters
}
/// launches the application
public static void main(String[] args)
{
GridBagLayoutDemo app = new GridBagLayoutDemo();
app.setSize(400, 300);
app.setLocationRelativeTo(null);
app.setVisible(true);
}
}
有什么想法吗?谢谢!
【问题讨论】:
-
GBC 是基于列的布局管理器,也许自定义 TableLayout 比 GBC 更好,特别是简单,甚至可以使用 SpringLayout(列和行)
标签: java swing constraints layout-manager gridbaglayout