【问题标题】:JPanel GridBagLayout start from top instead of centerJPanel GridBagLayout 从顶部而不是中心开始
【发布时间】:2021-02-14 00:32:25
【问题描述】:

我一直在尝试制作一个仪表板,其中主菜单按钮从仪表板顶部到底部列出,但设置

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

从面板的中心开始,而不是从顶部开始。我尝试设置gridBagConstraints.anchor = GridBagConstraints.FIRST_LINE_STARTGridBagConstraints.NORT 以及NORTHWEST,但没有任何效果。

由于菜单侧面有一个大面板,我不能让按钮自动适应(weighty=1 选项),否则按钮会变长。

有没有办法强制按钮制作一个列表,或者用另一种布局来做到这一点?

【问题讨论】:

  • 在底部放一个“空白”组件(即JPanel)并将其weighty设置为1.0
  • 你能把这个作为答案,以便我标记它吗?另外,感谢您的回答,这就是我需要的结果。

标签: java swing awt layout-manager gridbaglayout


【解决方案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我通常会让填充组件透明,但这是出于演示目的

【讨论】:

    猜你喜欢
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多