java - 无法使 GridBagLayout 按预期工作

标签 java swing

/**
 *  I'd like to achive following layout:
 *   +----------+----------+
 *   | Button 1 |          |
 *   +----------| Button 2 |
 *   | Button 3 |          |
 *   +----------+----------+
 *  with following code:
 */

JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JButton button;

button = new JButton("Button 1");
c.weightx = 0.5;
c.weighty = 0.5;
c.fill = GridBagConstraints.BOTH;
panel.add(button, c);

button = new JButton("Button 2");
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridheight = 2;
panel.add(button, c);

button = new JButton("Button 3");
c.gridwidth = 1;
panel.add(button, c);

/**
 *  but what I achive is:
 *   +----------+----------+
 *   | Button 1 | Button 2 |
 *   +----------+----------+|
 *   | Button 3 |
 *   +----------+
 */

/**
 *  However layout:
 *   +----------+----------+
 *   |          | Button 2 |
 *   + Button 1 +----------+
 *   |          | Button 3 |
 *   +----------+----------+
 *  is easily achieved as:
 */

JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JButton button;

button = new JButton("Button 1");
c.weightx = 0.5;
c.weighty = 0.5;
c.fill = GridBagConstraints.BOTH;
c.gridheight = 2;
panel.add(button, c);

button = new JButton("Button 2");
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridheight = 1;
panel.add(button, c);

button = new JButton("Button 3");
panel.add(button, c);

有什么线索吗?

问候,弗朗西斯

最佳答案

需要指定gridx和gridy,默认为0。

    button = new JButton("Button 1");
    c.weightx = 0.5;
    c.weighty = 0.5;
    c.fill = GridBagConstraints.BOTH;
    panel.add(button, c);

    button = new JButton("Button 3");
    c.gridy = 1;
    c.gridwidth = 1;
    panel.add(button, c);

    button = new JButton("Button 2");
    c.gridx = 1; c.gridy = 0;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.weighty = 1;c.gridheight = 2;
    panel.add(button, c);

关于java - 无法使 GridBagLayout 按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4358668/

相关文章:

java - 有没有一种优雅的方法可以在使用 Guava 转换 Collection 时删除空值?

java - 如何从数据库中插入图片到JTable

java - 如何在java对话框中使字体变粗?

java - JLabels(和其他东西)不会显示在 JFrame(多个 JFrame)的 JPanel 内

java - 主要次要版本 51.0 不受支持,但我的 JRE 是最新的

java - Android:如何设置 MenuButton 的监听器?

java - 使用西里尔字符的 IText PdfAction

java Clip 循环不工作

java - 从鼠标监听器方法调用时 repaint() 不起作用

java - JLabel,如何设置坐标