簡體   English   中英

如何使用 GridBagLayout 設置子面板與其容器的寬度相同?

[英]How to set sub panels have the same width as their container with GridBagLayout?

所以我有一個主要的 JPanel,我想將其用作更多面板的容器。 我希望子面板與其父面板具有相同的寬度,我嘗試使用 GridBagLayout 來實現它:

private JPanel createPanels() {
    JPanel content = new JPanel(new GridBagLayout());

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.anchor = GridBagConstraints.LINE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.gridwidth = 1;

    gbc.gridx = 0;
    gbc.gridy = 0;
    JPanel p1 = new JPanel();
    p1.add(new JLabel("Test"));
    p1.add(new JButton("+"));

    content.add(p1, gbc);

    return content;
}

使用這段代碼,我得到以下結果:

在此處輸入圖像描述

如您所見,剛剛創建的面板不適合其容器(綠色面板)的寬度。 我以為gbc.anchor = GridBagConstraints.LINE_START; gbc.fill = GridBagConstraints.HORIZONTAL; 線路將負責這樣做,但顯然他們沒有。

我怎樣才能做到這一點?

我對您的代碼做了一些更改並創建了以下 GUI。

例子

在您的代碼中,您創建了一個帶有FlowLayoutJPanel並將其放置在一個帶有GridBagLayoutJPanel中。 FlowLayout JPanel被視為一個 Swing 組件,因此它不會根據容器大小進行調整。

我在您的代碼中添加了一個main方法和一個JFrame以顯示差異。

這是我認為您想要的完整可運行代碼。

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class GridBagLayoutTest2 implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new GridBagLayoutTest2());
    }

    @Override
    public void run() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(createPanels(), BorderLayout.CENTER);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createPanels() {
        JPanel content = new JPanel(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.LINE_START;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridwidth = 1;
        gbc.insets = new Insets(5, 5, 5, 5);

        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 0.0;
        content.add(new JLabel("Test"), gbc);

        gbc.gridx++;
        gbc.weightx = 1.0;
        content.add(new JButton("+"), gbc);

        return content;
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM