0

似乎 JComboBox 是一个 Java 组件,它真的非常讨厌调整它的高度……我尝试了无数种set[Preferred|Minimum|Maximum]Size()不同的布局管理器的组合,直到下面的GroupLayout代码最终起作用:

JComboBox cmbCategories = new JComboBox(new String[] { "Category 1", "Category 2" });
...
layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
        .addComponent(cmbCategories, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
...
layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
        .addComponent(cmbCategories, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)

但是我现在切换到 JGoodies FormLayout,它再次拒绝调整该死的组合框的大小!我目前有以下代码:

JPanel contentPane = new JPanel();
contentPane.setLayout(new FormLayout("50dlu, $lcgap, 110dlu, $glue, " +
    "default, 1dlu, 45dlu, 1dlu, 45dlu", "2*(default, 0dlu), default, " +
    "$lgap, fill:30dlu, $lgap, default:grow"));
...
contentPane.add(cmbPanel, CC.xy(1, 7, CC.FILL, CC.FILL));

它在 JFormDesigner 编辑器中显示我想要的内容,但是在运行程序时它只是被设置回默认值!

那么我需要想出什么样的魔法骗局才能让它发挥作用?!我真的不想在 a 中重新定义所有内容两次GroupLayout,但是在尝试调整该死的组合框的大小 5 小时后,我正处于秃顶的边缘!

MTIA 给任何可以提供帮助的人:)

4

1 回答 1

2

首先我们必须避免在我们的组件中设置硬编码的大小,因为 Swing 被设计为与布局管理器一起使用,我们的应用程序必须能够在不同的平台、不同的屏幕分辨率、不同的PLaF和不同的字体中执行尺寸。组件大小和定位是布局经理的职责,而不是开发人员的职责。

现在,一般来说,当我们想为 Swing 组件设置首选大小时,我们不使用任何setXxxSize()方法,而是使用覆盖getPreferredSize()方法:

JComboBox comboBox = new JComboBox() {
    @Override
    public Dimension getPreferredSize() {
        return isPreferredSizeSet() ? 
                super.getPreferredSize() : new Dimension(100, 40);
    }
};

但是,这样做不会影响弹出窗口可见时列出的项目的大小:单元格仍然具有由组合框单元格渲染器确定的首选大小。因此,为了避免这种不良行为,更好的解决方案是:

例如:

JComboBox comboBox = new JComboBox();
comboBox.setPrototypeDisplayValue("This is a cell's prototype text");
comboBox.setRenderer(new DefaultListCellRenderer() {
    @Override
    public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        int width = c.getPreferredSize().width; // let the preferred width based on prototype value
        int height = 40;
        c.setPreferredSize(new Dimension(width, height));
        return c;
    }
});

我想再次强调,这是一种粗俗/肮脏的方式来调整我们的组合框的大小。恕我直言,最好不要弄乱组合框的高度,而只是玩以setPrototypeDisplayValue(...)PLaF 安全的方式设置首选宽度。

于 2014-10-25T23:27:04.113 回答