添加/更改影响父级 setBounds 的 JLabels [英] Adding/changing JLabels affecting parent's setBounds

查看:28
本文介绍了添加/更改影响父级 setBounds 的 JLabels的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Java 还是个新手,我很喜欢玩弄它,所以请就这点给我幽默一下.我了解布局管理器,但我对摆动机制感兴趣,所以我使用的是绝对定位.任何见解将不胜感激.

I'm still new to Java and I'm enjoying messing around with it, so please just humor me on this. I know about the layout manager but I'm interested in the mechanics of swing so I'm using absolute positioning. Any insights would be greatly appreciated.

因此,当我将 JLabel 添加到 JPanel 时,我注意到了一个令人讨厌的行为.例如,如果我这样设置:

So I've noticed an annoying behavior when I add a JLabel to a JPanel. For Example if I set it up like this:

JFrame frame=new JFrame("Test Frame");
frame.setSize(800,500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable (false);
JPanel conPane=new JPanel();
conPane.setLayout(null);
frame.setContentPane(conPane);
conPane.setBounds(0,0,1600,1000);
conTP.setFocusable(true);
frame.setVisible(true);

所以现在我移动 conPane 面板...

So now I move the conPane panel...

conPane.setBounds(-200,-200,1600,1000);

然后创建一个新的 JLabel....

And then make a new JLabel....

ImageIcon ico=new ImageIcon("directory/testimage.gif");
JLabel myLabel=new JLabel(ico);myLabel.setLayout(null);
myLabel.setBounds(300,300,200,200);

并将其添加到 conPane...

And add it to conPane...

conPane.add(myLabel);

它会将 conPane 重置回它的起始位置.基本上没有我的许可就在做 setBounds(0,0,1600,1000);

And it resets conPane back to it's starting position. Essentially doing setBounds(0,0,1600,1000) without my permission;

如果我移动标签、更改它的图标或几乎做任何涉及更改 conPane 子项的事情,也会发生这种情况.

It also happens if I move a label, change it's icon or pretty much do anything involving altering a child of conPane.

我怎样才能阻止它?

推荐答案

它会将 conPane 重置回它的起始位置

And it resets conPane back to it's starting position

本质上,这是错误的.这是错误的,因为你的假设是错误的:你假设

Essentially, that's wrong. It's wrong because your assumption is wrong: you assume that

contPane.setBounds(....)

一个效果,而实际上它没有:负责布局组件的 layoutManager 是其 的管理器(在这种情况下是 RootPaneLayout你绝对不想搞砸).无论您做什么,该经理都会将其设置为框架的大小(- 插图- 菜单栏).您可以通过为 contentPane 设置边框来形象化:

has an effect when actually it doesn't: the layoutManager that's responsible for laying out a component is the manager of its parent (which in this context is RootPaneLayout which you definitely don't want to mess up). That manager sets it to the size of the frame (- insets - menubar), no matter what you do. You can visualize that by setting a border to the contentPane:

contPane.setBorder(BorderFactory.createLineBorder(Color.RED, 5)); 

归根结底,绝对没有办法完全了解布局,即使您坚持不使用它来浪费时间.

At the end of the day, there is absolutely no way around learing all about layouts, even if you insist on wasting time by not using it.

这篇关于添加/更改影响父级 setBounds 的 JLabels的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆