问题
I want the user to input a maximum of 8 numbers as it is a field for Mobile number. This is my JTextField.
txtMobile = new JTextField();
txtMobile.setColumns(10);
txtMobile.setBounds(235, 345, 145, 25);
add(txtMobile);
While we're at it, how do I check for invalid characters like >> '^%$*
in a JTextField
?
1)Maximum Length
2)Accepts only numbers
3)Check for invalid characters
4)Check if it's a valid email address
Please help :D
回答1:
You could use a JFormattedField
, check out How to Use Formatted Text Fields, but they tend not to restrict the user from entering what ever they want, but instead does a post validation of the value to see if meets the needs of the format you sepcify
You could use a DocumentFilter
instead, which would allow you to filter the input in real time.
Take a look at Implementing a Document Filter and MDP's Weblog for examples
回答2:
Look at this sample example it will only accepts numbers as an input, as an answer to your second requirement.
public class InputInteger
{
private JTextField tField;
private JLabel label=new JLabel();
private MyDocumentFilter documentFilter;
private void displayGUI()
{
JFrame frame = new JFrame("Input Integer Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
tField = new JTextField(10);
((AbstractDocument)tField.getDocument()).setDocumentFilter(
new MyDocumentFilter());
contentPane.add(tField);
contentPane.add(label);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
@Override
public void run()
{
new InputInteger().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class MyDocumentFilter extends DocumentFilter{
private static final long serialVersionUID = 1L;
@Override
public void insertString(FilterBypass fb, int off
, String str, AttributeSet attr)
throws BadLocationException
{
// remove non-digits
fb.insertString(off, str.replaceAll("\\D++", ""), attr);
}
@Override
public void replace(FilterBypass fb, int off
, int len, String str, AttributeSet attr)
throws BadLocationException
{
// remove non-digits
fb.replace(off, len, str.replaceAll("\\D++", ""), attr);
}
}
来源:https://stackoverflow.com/questions/21570245/maximum-length-of-jtextfield-and-only-accepts-numbers