简体   繁体   English

为什么空布局和绝对位置在Java Swing中是不好的做法?

[英]Why null layout and absolute positions are bad practice in Java Swing?

I have code with null panel: 我有空面板的代码:

JPanel thePanel = new JPanel();
    thePanel.setLayout(null);

and I used setBounds(x, y, width, heigth), fe here: 我在这里使用setBounds(x,y,width,heigth),fe:

label2.setBounds(150, 220, 459, 311);

I read that this is not a good practice, can you tell me why? 我读到这不是一个好习惯,您能告诉我为什么吗? Is it only because when you want to add something between one component and another you have to set them positions again and again or is it something else? 仅仅是因为当您想要在一个组件和另一个组件之间添加某些内容时,您必须一次又一次地设置它们的位置还是其他内容?

I'd be very grateful for answer, thanks! 我非常感谢您的回答,谢谢! ;) ;)

There are multiple problems with absolute positioning: 绝对定位存在多个问题:

  • Different screen sizes and resolutions, what looks great on your machine would come out differently on another screen with a different resolution. 不同的屏幕尺寸和分辨率,在您的计算机上看起来不错的东西,在具有不同分辨率的另一个屏幕上的显示效果也不同。
  • In the same vein, what happens when a user resizes the screen because they want to run your application side by side with some other application (to copy paste or whatever) 同样,当用户调整屏幕大小时会发生什么,因为他们想与其他应用程序并排运行您的应用程序(复制粘贴或其他内容)
  • Different locales and font sizes, what happens to your labels when you use another locale, or another font, or change the font size. 不同的语言环境和字体大小,当您使用另一种语言环境,另一种字体或更改字体大小时,标签会发生什么情况。

There's probably more reasons, but using a layout manager makes sure that content is redistributed when windows are resized, or when content of a container changes, ... 可能还有更多原因,但是使用布局管理器可确保在调整窗口大小或更改容器内容时重新分配内容,...

Using absolute positioning is probably the easiest way in the beginning, but it pays to get to know the different layout managers and how they operate. 在开始时,使用绝对定位可能是最简单的方法,但是了解不同的布局管理器及其操作方式是值得的。 It will save you from a lot of headaches due to, for example, changing requirements. 例如,由于需求的变化,它将使您免于头疼。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM