Should I completely avoid the use of those methods?
I wouldn't say "avoid" them. I'd say that if you think you need them, you're probably doing something wrong. Component sizes are determined in context. For example, Text component sizes are determined by the number of rows and columns you specify, combined with the font you may have chosen. Your button and label size will be the size of the graphic, if you set one, or the space needed to display the text you set. Each component has a natural size, and the layout managers will use those to lay everything out without you needing to specify sizes. The main exception is the JScrollPane, which has a size independent of whatever it contains. For those, I will sometimes call setSize(), and let that size determine the initial window size, by calling JFrame.pack(). Usually, I will let the window size determine the JScrollPane size. The user will determine the size of the window. Many layout managers ignore the sizes you set anyway, so they often don't do much good.
定义这些方法是有原因的。那么什么时候使用它们呢?在什么情况下?为了什么目的?
我相信添加它们是为了给布局管理器提供提示。它们可能是由于历史原因而编写的,因为布局管理器是新的,人们并不完全信任它们。我认识一些开发人员,他们避免使用布局管理器,并手动放置所有东西,只是因为他们不想费心学习新的范例。这是个糟糕的主意。
使用这些方法的负面后果究竟是什么?(我只能考虑在不同屏幕分辨率的系统之间增加可移植性)。
它们是无效的,而且会产生糟糕的布局,物体会被挤压或拉伸到非自然的大小。而且布局会很脆弱。更改窗口大小有时会破坏布局,并将内容放在错误的位置。
I don't think any LayoutManager can exactly satisfy all desired layout needs. Do I really need to implement a new LayoutManager for every little variation on my layout ? You shouldn't "implement" a new LayoutManager. You should instantiate existing ones. I often use several layout managers in a single window. Each JPanel will have its own layout manager. Some people balk at nested layouts, because they're hard to maintain. When I use them, I give each one its own creation method to make it easier to see what each one does. But I never "implement" a layout manager. I just instantiate them.
如果4的答案是“是”,这是否会导致LayoutManager类的激增,从而变得难以维护?
如果你正在为布局中的轻微变化实现新的布局管理器类,那么你使用它们是错误的。如果你只是实现新的布局管理器,你可能做错了什么。我唯一一次扩展LayoutManager类,是向JScrollPane添加缩放滑块。
In a situation where I need to define proportions between children of a Component (eg, child1 should use 10% of space, child2 40% ,child3 50%), is it possible to achieve that without implementing a custom LayoutManager?
The JSplitPane has a way of specifying the percentage each component should get. The divider is movable by default, but you can turn that off if you want. I don't use that feature much. I usually have some components that take up a set size, and the rest of the space is taken up by a scroll pane. The scroll pane size will adjust with the window size. If you have two scroll panes side by side, you can put them in a JSplitPane and specify the percentage of new space given to each one as the user expands and contracts the windows.