2017-07-19 66 views
0

我有一個具有4個文本字段和一個按鈕的窗體的Java應用程序。我想知道是否有方法讓程序經常使用.isEmpty()來檢查字段是否已經有輸入,並且一旦所有字段中都有輸入,該按鈕將變爲可用於單擊?如何不斷驗證JTextField?

+1

您可以實現一個'DocumentListener'並檢查您的文本字段是否爲空。 – Flown

+0

你在暗示的是使用輪詢方法。你想要一個事件驅動的方法。 – Michael

回答

3

添加一個DocumentListener。

 JButton button = new JButton("Button"); 
     JTextField field = new JTextField(); 
     field.getDocument().addDocumentListener(new DocumentListener(){ 

      @Override 
      public void changedUpdate(DocumentEvent arg0) { 
       if(field.getText().isEmpty()){ 
        button.setEnabled(true); 
       } 
      } 

      @Override 
      public void insertUpdate(DocumentEvent arg0) { 
       if(field.getText().isEmpty()){ 
        button.setEnabled(true); 
       } 
      } 

      @Override 
      public void removeUpdate(DocumentEvent arg0) { 
       if(field.getText().isEmpty()){ 
        button.setEnabled(true); 
       } 
      } 

     }); 
+4

因爲String是對象,所以使用String :: equals而不是== ==。或者更好的使用'String :: isEmpty'。 – Flown

+1

@Flown我正要說相同的 – Shirkam

+0

Derp,還沒有喝過我的咖啡。感謝您指出了這一點。 – DCON