2017-07-26 120 views
0

我有一個組合框,它將處於只讀模式。我想爲該組合框設置一個默認值,指示組合框的用途(例如:組合框中默認文本爲「位置」的組合框,以及其他項目的數量,例如美國,印度,英國等)。 注意:默認值不應該是組合框中的其中一個項目。 我知道這是不可能的,如果組合框處於只讀模式。 如果有任何解決方法,請讓我知道。如何在Swt組合框中設置默認值?

如下圖所示,有一個組合框具有不同的變體,如A,B,C,D等,但組合框具有默認標籤'Variante'。

enter image description here

+0

您想在一個只讀組件中的值顯示的東西嗎? –

+0

@UsagiMiyamoto是的 –

回答

3

這可以使用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(); 
    } 

} 

結果:

enter image description here