2013-10-15 78 views
1

我正在製作一個GUI,其中我使用多個JTextfield實例來輸入來自用戶的輸入。我想指定這個特定的(例如:用戶名)文本字段是必填的。我怎樣才能做到這一點?在JTextField上添加約束條件

JLabel label_2 = new JLabel("User Name"); 
      label_2.setBounds(23, 167, 126, 21); 
      panel_1.add(label_2); 

    textField_2 = new JTextField(); 
      textField_2.setColumns(10); 
      textField_2.setBounds(178, 129, 210, 20); 
     panel_1.add(textField_2); 
+0

我猜你將需要經過對提交行動必填字段,並檢查它們是否包含值 – JohnnyAW

+0

你是如何處理在所有輸入的值文本字段? – UDPLover

+0

1)爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 2)Java GUI可能需要在多種平臺上工作,使用不同的屏幕分辨率並使用不同的PLAF。因此,它們不利於組件的準確放置。爲了組織強大的圖形用戶界面,請使用佈局管理器或[它們的組合](http://stackoverflow.com/a/5630271/418556)以及[空格]的佈局填充和邊框(http: //stackoverflow.com/q/17874717/418556)。 3)問題中空白圖像的目的是什麼? –

回答

1

當用戶與文本框完成,例如當他提交的數據,你可以驗證文本框,看它是否是空的。

例如,如果您使用提交按鈕。

submitButton.addActionLister(new ActionListner(){ 
    public void actionPerformed(ActionEvent ae){ 
     if(textField.getText().length() == 0){ 
      //notify user that mandatory field is empty. 
     } 

     //other validation checks. 
    } 
} 

OR

您可以添加焦點監聽到文本框。根據約束條件,每個字段都可以有不同的焦點丟失實現。

textfield.addFocusListener(new FocusListener(){ 
      @Override 
      public void focusGained(FocusEvent fe) { 
      // do whatever want like highlighting the field 
      } 

      @Override 
      public void focusLost(FocusEvent fe) { 
       //check for constraint as the user is done with this field. 
      } 
}); 
0
JLabel label_2 = new JLabel("User Name"); 
label_2.setBounds(23, 167, 126, 21); 
panel_1.add(label_2); 

textField_2 = new JTextField(); 
textField_2.setColumns(10); 
textField_2.setBounds(178, 129, 210, 20); 
panel_1.add(textField_2); 

submit.addActionListener(this); 

} 

    public void actionPerformed(ActionEvent e) 
    { 
     //check the text field 
     if(textField_2.getText().length()==0) 
       { 
        //user_name not set 
       } 
     else 
       { 
       //user_name is set 
       } 

    }