【问题标题】:How to set Default value in Swt Combo box?如何在 Swt 组合框中设置默认值?
【发布时间】:2017-07-26 22:31:33
【问题描述】:

我有一个组合框,它将处于只读模式。我想为该组合框设置一个默认值,指示组合框的用途(例如:一个位置组合,默认文本为“位置”,组合框中有许多其他项目,如美国、印度、英格兰等)。 注意:默认值不应是组合框中的项目之一。 我知道如果组合框处于只读模式是不可能的。 请让我知道是否有任何解决方法。

如下图所示,有一个组合框,其中包含不同的变体,如 A、B、C、D 等,但组合框的默认标签为“Variante”。

【问题讨论】:

  • 你想在只读组件的值上显示一些东西?
  • @UsagiMiyamoto 是的

标签: java swt


【解决方案1】:

这可以使用CCombo 来实现。如果您使用setItems(String[]) 设置组合上的项目,在使用setText(String) 之前,您将在组合中看到一个默认值,它不是列表中的项目之一。

请注意,当您调用getSelectionIndex() 时,返回值将是-1,因为尚未选择任何项目,并且一旦选择了项目,默认值将不再存在。

public class CComboDefaultTextTest {

    public static void main(final String[] args) {
        final Display display = new Display();
        final Shell shell = new Shell(display);
        shell.setLayout(new GridLayout());

        final Composite baseComposite = new Composite(shell, SWT.NONE);
        baseComposite
                .setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        baseComposite.setLayout(new GridLayout());

        final CCombo combo = new CCombo(baseComposite, SWT.READ_ONLY
                | SWT.BORDER);
        combo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
        // Be sure to do this before calling setText()
        combo.setItems(new String[] { "item 1", "item 2", "item 3" });
        combo.setText("Default");

        System.out.println(combo.getSelectionIndex());

        shell.pack();
        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
        display.dispose();
    }

}

结果:

【讨论】:

    猜你喜欢
    • 2017-10-03
    • 2016-04-29
    • 2014-02-14
    • 2014-02-15
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    相关资源
    最近更新 更多