Java GridBagLayout-GridBagConstraints不起作用

Java GridBagLayout-GridBagConstraints不起作用,java,swing,layout-manager,gridbaglayout,Java,Swing,Layout Manager,Gridbaglayout,我试图使用GridBagLayout,但是GridBagConstraints对象没有显示任何效果。我想要一个按钮来填充水平空间。有什么想法吗 static class Five extends JFrame { public Five() { setSize(300, 400); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new GridBagLayout());

我试图使用
GridBagLayout
,但是
GridBagConstraints
对象没有显示任何效果。我想要一个按钮来填充水平空间。有什么想法吗

static class Five extends JFrame {

    public Five() {
        setSize(300, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 0;
        c.fill = GridBagConstraints.HORIZONTAL;

        JButton button = new JButton("Long-Named Button 4");

        add(button, c);

        setVisible(true);
    }

这项工作,详情见评论:

import java.awt.*;
import javax.swing.*;

public class Five extends JFrame {

    public Five() {
        setSize(300, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        // best to do all important stuff in a panel added to the frame
        JPanel gui = new JPanel(new GridBagLayout()); 
        setContentPane(gui);

        GridBagConstraints c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 0;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 1d; // fixes the problem

        JButton button = new JButton("Long-Named Button 4");

        add(button, c);
        pack(); // should always be done after all components are added

        setVisible(true);
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                new Five();
            }
        };
        SwingUtilities.invokeLater(r);
    }
}
更多提示:
  • 扩展
    JFrame
    没有好的理由。在这种情况下,只需对标准框架的实例进行相关的添加等
  • 要使按钮变大,请设置大图标、大插图或大字体。要使框架更大,请在
    gui
    面板周围添加
    EmptyBorder
  • “有什么想法吗?”两个。1) 为了更快地获得更好的帮助,请发布一个or。对于这种情况,这意味着-添加一个
    main(..)
    方法结束相关导入。2) 发布一个屏幕截图(或一个链接)的图形用户界面拉伸比自然大小更宽。如果它有助于解决问题,请。