gpt4 book ai didi

java swing - 使用不同的布局管理器时布局奇怪

转载 作者:行者123 更新时间:2023-11-29 07:23:19 26 4
gpt4 key购买 nike

有点奇怪,看看我是否执行以下操作:

import javax.swing.*;
public class FunkyButtonLayout {
public static void main(String[] args) {
JFrame frame = new JFrame("");
JPanel j0 = new JPanel(); // j0 gets added to the root pane
j0.setLayout(null);
JPanel j1 = new JPanel(); // j1 gets added to j0
j1.setLayout(null);
JButton b1 = new JButton(""); // b1 gets added to j1
j1.add(b1);
b1.setBounds(0, 0, 40, 32); // b1 is big
j0.add(j1);
j1.setBounds(0, 0, 32, 32); // j1 is not so big - b1 gets 'trimmed'
frame.getContentPane().setLayout(null); // <- seems to be needed :-(
frame.getContentPane().add(j0);
j0.setBounds(10, 10, 32, 32); // end result: a 32x32 button with
frame.setSize(125, 125); // a trimmed right border
frame.setVisible(true); // in the top-left corner
}
}

除了能够使用布局管理器将 j0 定位在根 Pane 中之外,我几乎得到了我正在寻找的东西。如果我改变

        frame.getContentPane().setLayout(null);

线到

        frame.getContentPane().setLayout(new java.awt.FlowLayout());

我看到 j0 在屏幕中间绘制为 1x1 像素:-(

有什么想法吗?请注意,这不仅仅是 FlowLayout 的事情——几乎每个布局管理器都会把它搞砸。

我真的很想获得“在一侧修剪边框”按钮的净效果 - 它允许我做工具栏按钮集群的事情(cage fighter 试图摆脱的那种事情)原生外观的按钮控件 - 由于操作系统级别的皮肤,我看不到另一种方法。所以任何想法表示赞赏:-)

最佳答案

如果将布局管理器设置为 null,则必须显式设置容器的首选大小(这就是它显示如此小的原因)。

如果您在组件上使用 setBounds,您将覆盖父容器的布局管理器所做的工作。

我会删除对 setBounds 的所有调用和对 setLayout(null) 的所有调用,并尝试在仅使用布局管理器后实现您的效果。

关于java swing - 使用不同的布局管理器时布局奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/539567/

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