问题
I have code with null panel:
JPanel thePanel = new JPanel();
thePanel.setLayout(null);
and I used setBounds(x, y, width, heigth), f.e here:
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! ;)
回答1:
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.
来源:https://stackoverflow.com/questions/40311819/why-null-layout-and-absolute-positions-are-bad-practice-in-java-swing