问题
I am making a GUI, in which I am using a number of JTextfield
instances to enter the input from the user. I want to specify that this particular (for example : user name) text field is mandatory to fill. How can I do this?
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);
回答1:
you can also use JFormattedTextField
http://docs.oracle.com/javase/7/docs/api/javax/swing/JFormattedTextField.html
回答2:
When the user is done with the textfield, for example when he submits the data, you can validate the textfield to see if it's empty.
For example, if you are using a submit button.
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
You can add a focus listener to the textfields. And every field can have different focus lost implementations depending on the constraint.
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.
}
});
回答3:
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
}
}
来源:https://stackoverflow.com/questions/19378917/adding-constraint-on-jtextfield