gpt4 book ai didi

java - GridBag布局问题

转载 作者:行者123 更新时间:2023-12-01 16:51:18 26 4
gpt4 key购买 nike

我正在尝试使用 GridBagLayout。我需要一个垂直和水平居中的 JLabel - 这很简单,我什至不需要创建任何 GridBagConstraints。我还想在右下角放置一个 JButton,当我尝试这样做时,我的居中面板向左移动或按钮向上移动。

EXPECTING     GETTING THIS  OR THIS
+-----------+ +-----------+ +-----------+
| | | | | |
| | | | | |
| | | | | |
| +---+ | | +---+ | | +---+ |
| | | | | | | | | | | |
| +---+ | | +---+ | | +---++---+|
| | | | | | ||
| | | | | +---+|
| +---+ | +---+ | |
| | | | | | | |
+-------+---+ +-------+---+ +-----------+

bigPanel = new JPanel();
bigPanel.setPreferredSize(new Dimension(320, 640));
bigPanel.setLayout(new GridBagLayout());

label = new JLabel();
label.setPreferredSize(new Dimension(100,95));

button = new JButton();
button.setPreferredSize(new Dimension(100,25));

GridBagConstraints c = new GridBagConstraints();

c.anchor = GridBagConstraints.CENTER;
bigPanel.add(label, c);

c.anchor = GridBagConstraints.LAST_LINE_END;
bigPanel.add(button, c);

我还尝试使用此处描述的其他约束http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html但每次都会出现问题。

最佳答案

anchor如果组件未填充单元格,则设置组件在其单元格内的位置。

您尚未定义布局的网格。默认行为是从左到右添加组件。

这里是一个使用 GridBagLayout 实现您想要的效果的示例。标签和按钮放置在填充面板的同一单元格中。

public class Test extends JPanel {
public Test() {
super();
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWeights = new double[] { 1.0 }; // expands the 1rst cell of the layout on the vertical axis
gridBagLayout.rowWeights = new double[] { 1.0 }; // expands the 1rst cell of the layout on the horizontal axis
setLayout(gridBagLayout);

JLabel label = new JLabel("test");
label.setOpaque(true);
label.setBackground(Color.RED);
label.setPreferredSize(new Dimension(100, 95));
GridBagConstraints gbc_label = new GridBagConstraints();
gbc_label.gridx = 0; // set label cell (0,0)
gbc_label.gridy = 0;
gbc_label.insets = new Insets(0, 0, 5, 5);

add(label, gbc_label);

JButton button = new JButton("button");
GridBagConstraints gbc_button = new GridBagConstraints();
gbc_button.gridx = 0; // set buttoncell (0,0)
gbc_button.gridy = 0;
gbc_button.anchor = GridBagConstraints.SOUTHEAST;

add(button, gbc_button);
button.setPreferredSize(new Dimension(100, 25));
}
}

关于java - GridBag布局问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39611764/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com