簡體   English   中英

JPanel GridBagLayout 從頂部而不是中心開始

[英]JPanel GridBagLayout start from top instead of center

我一直在嘗試制作一個儀表板,其中主菜單按鈕從儀表板頂部到底部列出,但設置

    gridBagConstraints.gridx = 10;
    gridBagConstraints.gridy = 0;

從面板的中心而不是頂部開始。 我嘗試設置gridBagConstraints.anchor = GridBagConstraints.FIRST_LINE_STARTGridBagConstraints.NORT以及NORTHWEST ,但這沒有任何作用。

由於菜單側面有一個大面板,我不能讓按鈕自動適應( weighty=1選項),否則按鈕會變長。

有沒有辦法強制按鈕制作一個列表,或者用另一種布局來做到這一點?

這是一種常見的模式。 通常,當您想強制將組件對齊到特定邊緣時,您可以在另一側放置一個填充組件並將其設置為填充剩余的空白空間

填充

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.setLayout(new GridBagLayout());
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridx = 0;
                gbc.gridwidth = GridBagConstraints.REMAINDER;

                frame.add(new JLabel("This is a line"), gbc);
                frame.add(new JLabel("This is another line"), gbc);
                frame.add(new JLabel("This is show off line"), gbc);

                gbc.weighty = 1;
                JPanel filler = new JPanel();
                filler.setBackground(Color.RED);

                frame.add(filler, gbc);

                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

ps我通常會讓填充組件透明,但這是為了演示目的

暫無
暫無

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

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