有几次,我因为建议使用以下方法而受到批评:

setPreferredSize setMinimumSize setMaximumSize

Swing组件。当我想要定义显示的组件之间的比例时,我没有看到任何替代它们的使用。有人告诉我:

对于布局,答案总是一样的:使用合适的 LayoutManager

我在网上搜索了一下,但我还没有找到任何关于这个主题的全面分析。我有以下几个问题:

Should I completely avoid the use of those methods? The methods have been defined for a reason. So when should I use them? In which context? For what purposes? What exactly are the negative consequences of using those methods? (I can only think adding portability between systems with different screen resolution). 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 ? If the answer to 4 is "yes", won't this lead to a proliferation of LayoutManager classes which will become difficult to maintain? 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?


当前回答

我的看法与公认的答案不同。

1)我应该完全避免使用这些方法吗?

不要避免!它们的作用是向布局管理器表达组件的大小限制。如果你不使用任何布局管理器,你可以避免使用它们,并尝试自己管理可视化布局。

不幸的是,Swing没有提供合理的默认尺寸。但是,与其设置组件的尺寸,不如使用合理的默认值降低您自己的组件。(在这种情况下,在你的子类中调用setXXX。)或者,您可以重写getXXX方法以达到同样的效果。

2)定义方法是有原因的。那么什么时候使用它们呢?在什么情况下?为了什么目的?

Always. When you create a component, set its realistic min/preferred/max size according to the use of that component. For example, if you have a JTextField for entering country symbols such as UK, its preferred size shall be as wide to fit two chars (with the current font, etc.) but probably it is meaningless to let it grow any bigger. After all, country symbols are two chars. As opposite, if you have a JTextField for entering e.g. a customer name, it can have a preferred size for like the pixel size for 20 chars, but can grow to bigger if the layout is resized, so set the maximum size to more. At the same time, having a 0px wide JTextField is pointless, so set a realistic minimum size (I would say the pixel size of 2 chars).

3)使用这些方法的负面后果究竟是什么?

(我只能考虑在不同屏幕分辨率的系统之间增加可移植性)。

没有负面后果。这些是布局管理器的提示。

4)我认为任何LayoutManager都不能完全满足所有所需的布局需求。

我真的需要为我的布局上的每个小变化实现一个新的LayoutManager吗?

不,绝对不是。通常的方法是级联不同的基本布局管理器,如水平布局和垂直布局。

例如,下面的布局:

<pre>
+--------------+--------+
| ###JTABLE### | [Add]  | 
| ...data...   |[Remove]|
| ...data...   |        |
| ...data...   |        |
+--------------+--------+
</pre>

有两部分。左右部分为水平布局。右边的部分是一个添加到水平布局的JPanel,这个JPanel有一个垂直布局,垂直布局按钮。

当然,在现实生活的布局中,这可能会变得棘手。因此,如果你要开发严肃的东西,基于网格的布局管理器(如MigLayout)会更好。

5)如果4的答案是“是”,这是否会导致LayoutManager类的激增,这将变得难以维护?

不,你绝对不应该开发布局管理器,除非你需要一些非常特别的东西。

6)在需要定义比例的情况下……

在一个组件的子组件之间(例如,child1应该使用10%的空间,child2应该使用40%的空间,child3应该使用50%的空间),是否可以在不实现自定义LayoutManager的情况下实现这一目标?

基本上,一旦设置了正确的首选大小,您可能不希望在百分比中执行任何操作。简单地说,因为百分比是没有意义的(例如,有一个JTextField的窗口大小的10%是没有意义的-因为一个可以缩小窗口,使JTextField成为0px宽,或可以展开窗口,使JTextField是跨两个显示在一个多显示设置)。

但是,有时你可能会使用百分比来控制gui中较大的构建块的大小(例如面板)。

您可以使用JSplitPane,在这里您可以预先设置两边的比例。或者,您可以使用MigLayout,它允许您以百分比、像素和其他单位设置此类约束。

其他回答

Should I completely avoid the use of those methods? Yes for application code. The methods have been defined for a reason. So when should I use them? In which context? For what purposes? I don't know, personally I think of it as an API design accident. Slightly forced by compound components having special ideas about child sizes. "Slightly", because they should have implemented their needs with a custom LayoutManager. What exactly are the negative consequences of using those methods? (I can only think adding portability between systems with different screen resolution.) Some (incomplete, and unfortunately the links are broken due to migration of SwingLabs to java.net) technical reasons are for instance mentioned in the Rules (hehe) or in the link @bendicott found in his/her comment to my answer. Socially, posing tons of work onto your unfortunate fellow who has to maintain the code and has to track down a broken layout. 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? Yes, there are LayoutManagers powerful enough to satisfy a very good approximation to "all layout needs". The big three are JGoodies FormLayout, MigLayout, DesignGridLayout. So no, in practice, you rarely write LayoutManagers except for simple highly specialized environments. If the answer to 4 is "yes", won't this lead to a proliferation of LayoutManager classes which will become difficult to maintain? (The answer to 4 is "no".) In a situation where I need to define proportions between children of a Component (for example, child 1 should use 10% of space, child 2 40%, child 3 50%), is it possible to achieve that without implementing a custom LayoutManager? Any of the Big-Three can, can't even GridBag (never bothered to really master, too much trouble for too little power).

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.

大多数人对这些方法知之甚少。您绝对不应该忽略这些方法。这取决于布局管理器是否遵守这些方法。这个页面有一个表,显示了哪些布局管理器尊重哪些方法:

http://thebadprogrammer.com/swing-layout-manager-sizing/

我已经写了8年多的Swing代码,JDK中包含的布局管理器一直满足我的需求。我从来没有需要第三方布局管理器来实现我的布局。

我会说,你不应该尝试给布局管理器提示这些方法,直到你确定你需要他们。做你的布局,不给任何大小提示(即让布局管理器做它的工作),然后你可以做一些小的修改,如果你需要。

如果你在Java Swing的布局上遇到了麻烦,那么我可以强烈推荐由Karsten Lentzsch免费提供的JGoodies FormLayout,它是Forms免费软件库的一部分。

这个非常流行的布局管理器非常灵活,可以开发非常精致的Java ui。

您将在这里找到Karsten的文档,以及eclipse的一些相当不错的文档。

以下是一些启发:

Don't use set[Preferred|Maximum|Minimum]Size() when you really mean to override get[Preferred|Maximum|Minimum]Size(), as might be done in creating your own component, shown here. Don't use set[Preferred|Maximum|Minimum]Size() when you could rely on a component's carefully overridden getPreferred|Maximum|Minimum]Size, as shown here and below. Do use set[Preferred|Maximum|Minimum]Size() to derive post-validate() geometry, as shown below and here. If a component has no preferred size, e.g. JDesktopPane, you may have to size the container, after invoking pack(), but any such choice is arbitrary. A comment may help clarify the intent. Consider alternate or custom layouts when you find that you would have to loop through many components to obtain derived sizes, as mentioned in these comments.

import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.KeyboardFocusManager;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

/**
 * @see https://stackoverflow.com/questions/7229226
 * @see https://stackoverflow.com/questions/7228843
 */
public class DesignTest {

    private List<JTextField> list = new ArrayList<JTextField>();
    private JPanel panel = new JPanel();
    private JScrollPane sp = new JScrollPane(panel);

    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                DesignTest id = new DesignTest();
                id.create("My Project");
            }
        });
    }

    private void addField(String name) {
        JTextField jtf = new JTextField(16);
        panel.add(new JLabel(name, JLabel.LEFT));
        panel.add(jtf);
        list.add(jtf);
    }

    private void create(String strProjectName) {
        panel.setLayout(new GridLayout(0, 1));
        addField("First Name:");
        addField("Last Name:");
        addField("Address:");
        addField("City:");
        addField("Zip Code:");
        addField("Phone:");
        addField("Email Id:");
        KeyboardFocusManager.getCurrentKeyboardFocusManager()
            .addPropertyChangeListener("permanentFocusOwner",
            new FocusDrivenScroller(panel));
        // Show half the fields
        sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        sp.validate();
        Dimension d = sp.getPreferredSize();
        d.setSize(d.width, d.height / 2);
        sp.setPreferredSize(d);

        JInternalFrame internaFrame = new JInternalFrame();
        internaFrame.add(sp);
        internaFrame.pack();
        internaFrame.setVisible(true);

        JDesktopPane desktopPane = new JDesktopPane();
        desktopPane.add(internaFrame);

        JFrame frmtest = new JFrame();
        frmtest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmtest.add(desktopPane);
        frmtest.pack();
        // User's preference should be read from java.util.prefs.Preferences
        frmtest.setSize(400, 300);
        frmtest.setLocationRelativeTo(null);
        frmtest.setVisible(true);
        list.get(0).requestFocusInWindow();
    }

    private static class FocusDrivenScroller implements PropertyChangeListener {

        private JComponent parent;

        public FocusDrivenScroller(JComponent parent) {
            this.parent = parent;
        }

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            Component focused = (Component) evt.getNewValue();
            if (focused != null
                && SwingUtilities.isDescendingFrom(focused, parent)) {
                parent.scrollRectToVisible(focused.getBounds());
            }
        }
    }
}