我正在尝试使用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,只需对标准框架的实例进行相关的添加等即可。
要使按钮变大,请设置大图标,大插图或大字体。要使框架更大,请在EmptyBorder面板周围添加一个gui

09-15 14:48