2014-03-07 32 views
4

我還有一個問題。我使用ModifyListener作爲一個文本字段來激活和取消激活swt對話框中的OK按鈕。它效果很好。如何結合並驗證swt對話框的兩個文本字段?

現在我想爲另一個文本框添加ModifyListener。我希望只有在兩個文本字段中最少有一個字符時纔會激活OK按鈕。

這是兩個領域的代碼:

descriptionText.addModifyListener(new ModifyListener(){ 

    public void modifyText(ModifyEvent e) { 
     Text text = (Text) e.widget; 

     if (text.getText().length() == 0) { 

      getButton(IDialogConstants.OK_ID).setEnabled(false); 
     } 

     if (text.getText().length() >= 1) { 

      getButton(IDialogConstants.OK_ID).setEnabled(true); 
     } 
    } 
}); 

}

第二場:

我知道這doesn't工作,因爲有之間沒有依賴關係兩個按鈕。 我如何將它組合?

我想在兩個modifylistener都檢測字符時設置ok鍵false。 如果我刪除一個測試區域中的所有字符,則必須再次禁用該按鈕。

謝謝你。

回答

4

您可以使用兩個Text領域相同Listener,並將其添加爲SWT.KeyUp

public static void main(String[] args) 
{ 
    final Display display = new Display(); 
    Shell shell = new Shell(display); 
    shell.setText("StackOverflow"); 
    shell.setLayout(new FillLayout(SWT.VERTICAL)); 

    final Text first = new Text(shell, SWT.BORDER); 
    final Text second = new Text(shell, SWT.BORDER); 
    final Button button = new Button(shell, SWT.PUSH); 
    button.setText("disabled"); 
    button.setEnabled(false); 

    Listener listener = new Listener() 
    { 
     @Override 
     public void handleEvent(Event e) 
     { 
      String firstString = first.getText(); 
      String secondString = second.getText(); 

      button.setEnabled(!isEmpty(firstString) && !isEmpty(secondString)); 
      button.setText(button.isEnabled() ? "enabled" : "disabled"); 
     } 
    }; 

    first.addListener(SWT.KeyUp, listener); 
    second.addListener(SWT.KeyUp, listener); 

    shell.pack(); 
    shell.setSize(300, shell.getSize().y); 
    shell.open(); 

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

private static boolean isEmpty(String input) 
{ 
    if(input == null) 
     return true; 
    else 
     return input.trim().isEmpty(); 
} 

是這樣的:

enter image description here enter image description here


代碼將基本上(在每個關鍵筆畫上)檢查是否兩個Text s是空的。如果是這樣,請禁用Button,否則啓用它。

+0

謝謝@Baz,你讓我的一天:) – JonnyBeton

+0

@JonnyBeton不客氣。這似乎並不需要太多的時間來做你的一天:D – Baz