gpt4 book ai didi

java - GridBagConstraints 如何处理重叠对象?

转载 作者:行者123 更新时间:2023-12-01 09:57:28 25 4
gpt4 key购买 nike

此代码生成三个按钮。按钮“一”出现在“北”并部分覆盖位于东的按钮“二”。按钮三出现在西南方。如何获得按钮 1 和 2 重叠但没有按钮 3 的相同布局?

import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JButton;
import javax.swing.JFrame;

public class GridBagButtons {
private static final Insets insets = new Insets(0, 0, 0, 0);

public static void main(final String args[]) {
final JFrame frame = new JFrame("GridBagLayout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
JButton button;
// Row One - Three Buttons
button = new JButton("One");
addComponent(frame, button, 0, 0, 2, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH);
button = new JButton("Two");
addComponent(frame, button, 1, 0, 1, 2, GridBagConstraints.CENTER, GridBagConstraints.BOTH);

button = new JButton("Three");
addComponent(frame, button, 0, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH); //Comment out this

frame.setSize(500, 200);
frame.setVisible(true);
}
private static void addComponent(Container container, Component component, int gridx, int gridy,
int gridwidth, int gridheight, int anchor, int fill) {
GridBagConstraints gbc = new GridBagConstraints(gridx, gridy, gridwidth, gridheight, 1.0, 1.0,
anchor, fill, insets, 0, 0);
container.add(component, gbc);
}
}

注释按钮三会更改布局。按钮一完全覆盖按钮二。 [修改]代码来自这里http://www.java2s.com/Tutorial/Java/0240__Swing/UsingGridBagConstraints.htm

最佳答案

尝试在 GridBagLayout 构造函数中显式设置网格大小。

frame.setLayout(new GridBagLayout(2, 2));

关于java - GridBagConstraints 如何处理重叠对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37074664/

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