如何在 Swt 组合框中设置默认值?

How to set Default value in Swt Combo box?

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

如下图所示,组合框有不同的变体,如 A、B、C、D 等,但组合框具有默认标签 'Variante'。

这可以使用 CCombo. If you set the items on the combo using setItems(String[]), before you use 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();
    }

}

结果: