GridBagLayout - GridBagConstraints不起作用

时间:2016-09-15 12:19:38

标签: java swing layout-manager gridbaglayout

我尝试使用event.timestamp,但GridBagLayout个对象没有显示任何效果。我想要一个按钮来填充水平空间。任何想法?

GridBagConstraints

1 个答案:

答案 0 :(得分:3)

这有效,评论中有详细信息:

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);
    }
}

进一步提示:

  1. 在这种情况下,扩展JFrame没有好的理由,只需对标准框架的实例进行相关的添加等。
  2. 要使按钮变大,请设置一个大图标,大插图或大字体。要使框架更大,请在EmptyBorder面板周围添加gui