BorderLayout中心命令不会居中 [英] BorderLayout center command won't center

查看:154
本文介绍了BorderLayout中心命令不会居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 JFrame 的中心将两个 JButton 彼此相邻,赢了重新调整 JFrame 的大小时,不要重新调整按钮的大小。

I am trying to place two JButtons next to each other in the center of a JFrame, that won't re-size the buttons when the JFrame is re-sized.

要做到这一点,我放了两个具有 FlowLayout 的面板中的按钮,然后放置在具有中心 BorderLayout 的面板中。

To do this I placed the two buttons in a panel with a FlowLayout, that is then placed in a panel with a center BorderLayout.

但是,以下代码不会在 BorderLayout 的中心显示所选面板。

However the following code won't display the chosen panel in the center of the BorderLayout.

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class test extends JFrame {

    private JPanel panel1 = new JPanel();
    private JPanel panel2 = new JPanel();
    private JButton button1 = new JButton("one");
    private JButton button2 = new JButton("two");

    public test() {
        panel1.setLayout(new FlowLayout());
        panel1.add(button1);
        panel1.add(button2);

        panel2.setLayout(new BorderLayout());
        panel2.add(panel1, BorderLayout.CENTER);

        this.add(panel2);
    }

    public static void main(String[] args) {
        test frame = new test();
        frame.setVisible(true);
        frame.setSize(400, 400);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}


推荐答案

设置 GridBagLayout panel1

 panel1.setLayout(new GridBagLayout());

编辑:

@trashgod:I必须弄清楚默认约束是如何做到的。

@trashgod : I have to figure out how the default constraints do it.

因为字段 GridBagLayout.defaultConstraints


this field包含一个包含默认
值的gridbag约束实例,因此如果一个组件没有与它关联
的gridbag约束,那么该组件将被分配
defaultConstraints的副本。

This field holds a gridbag constraints instance containing the default values, so if a component does not have gridbag constraints associated with it, then the component will be assigned a copy of the defaultConstraints.

在正常情况下,必须创建 GridBagConstraints 对象并设置字段以指定每个对象上的约束

In normal practice, one must have to create GridBagConstraints object and set fields to specify the constraints on each object.

引用教程



组件上设置约束的首选方法是使用Container.add变体,传递
GridBagConstraints对象

The preferred approach to set constraints on a component is to use the Container.add variant, passing it a GridBagConstraints object

这篇关于BorderLayout中心命令不会居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆