请教如何将textField设置为只能输入数字
1个回答
展开全部
我是用的键盘监听
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test45 extends JFrame implements KeyListener {
JTextField tf = new JTextField(20);
int limit = 15;
private static Pattern NUM_PATTERN = Pattern.compile("\\d*");
public Test45() {
JPanel jp = new JPanel();
tf.addKeyListener(this);
jp.add(tf);
getContentPane().add(jp);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(new Dimension(400, 300));
setVisible(true);
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
String str = tf.getText();
Matcher m = NUM_PATTERN.matcher(str);
if (!m.matches()) {
getToolkit().beep();
e.consume();
System.out.println("only number allowed!");
JOptionPane.showMessageDialog(null, "only number allowed!");
str = str.substring(0, str.length() - 1);
tf.setText(str);
}
}
public void keyPressed(KeyEvent e) {
}
public static void main(String[] a) {
new Test45();
}
}
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test45 extends JFrame implements KeyListener {
JTextField tf = new JTextField(20);
int limit = 15;
private static Pattern NUM_PATTERN = Pattern.compile("\\d*");
public Test45() {
JPanel jp = new JPanel();
tf.addKeyListener(this);
jp.add(tf);
getContentPane().add(jp);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(new Dimension(400, 300));
setVisible(true);
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
String str = tf.getText();
Matcher m = NUM_PATTERN.matcher(str);
if (!m.matches()) {
getToolkit().beep();
e.consume();
System.out.println("only number allowed!");
JOptionPane.showMessageDialog(null, "only number allowed!");
str = str.substring(0, str.length() - 1);
tf.setText(str);
}
}
public void keyPressed(KeyEvent e) {
}
public static void main(String[] a) {
new Test45();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询