[英]How to restrict user to enter digits or special charater or blank or space in JTextField in Java Swing?
I am working on a project in Java Swing. 我正在使用Java Swing中的一个项目。 Now there is a text field for user name. 现在有一个用于用户名的文本字段。 I want to validate that text field so that user can't enter digits or special character or blank or space . 我想验证该文本字段,以便用户不能输入数字或特殊字符或空格或空格 。 In short I want a restriction such that user can't enter anything other than alphabets. 简而言之,我想要一个限制,使用户只能输入字母以外的任何内容。 The database is MS Access and table name is "test" and there is only one column named "sname". 该数据库是MS Access,表名称是“ test”,并且只有一列名为“ sname”。 As I am a beginner, simpler techniques will be appreciated.Thanks in advance. 我是一个初学者,请先使用简单的技术。
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
public class Ex_test extends JFrame implements ActionListener
{
public static void main(String[] args)
{
Ex_test ob=new Ex_test();
}
JTextField tf1;
JButton b1;
int num1;
public Ex_test()
{
super("test");
setLayout(new FlowLayout());
tf1=new JTextField(20);
add(tf1);
b1=new JButton("ok");
add(b1);
setSize(500,500);
setVisible(true);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if (ae.getActionCommand()=="ok")
{
try
{
String str=tf1.getText();
Connection con;
PreparedStatement ps;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:test");
ps=con.prepareStatement("insert into test values('"+str+"')");
ps.executeUpdate();
con.close();
ps.close();
JOptionPane.showMessageDialog(null,"DATA SUBMITTED SUCCESSFULLY.");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,"Exception Occurred.");
}
}
}
}
Use a JFormattedTextField. 使用JFormattedTextField。 Read the section from the Swing tutorial on How to Use Formatted Text Fields for more information and examples. 阅读Swing教程中有关如何使用格式文本字段的部分, 以获取更多信息和示例。
You can use a MaskFormatter
to specify that you only want to allow alphabetic characters. 您可以使用MaskFormatter
来指定只允许字母字符。
Try something like this - i used regex which validates input from user, more about regex you will find here : http://www.vogella.com/tutorials/JavaRegularExpressions/article.html 尝试这样的事情-我使用了正则表达式来验证用户的输入,有关正则表达式的更多信息,您可以在这里找到: http : //www.vogella.com/tutorials/JavaRegularExpressions/article.html
try
{
String str=tf1.getText();
if ( !(str.matches("[a-zA-Z]+"))) {
JOptionPane.showMessageDialog(null,"Please insert only characters.");
tf1.setText("");
}else{
Connection con;
PreparedStatement ps;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:test");
ps=con.prepareStatement("insert into test values('"+str+"')");
ps.executeUpdate();
con.close();
ps.close();
JOptionPane.showMessageDialog(null,"DATA SUBMITTED SUCCESSFULLY.");}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,"Exception Occurred.");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.