2013-10-15 82 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 
       } 

    }