在JTextField上添加约束

时间:2013-10-15 10:28:34

标签: java swing constraints jtextfield

我正在创建一个GUI,我在其中使用了许多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);

3 个答案:

答案 0 :(得分:2)

答案 1 :(得分: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.
          }
 });

答案 2 :(得分: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
              }

   }