java swing 怎么设置文本框只能输入数字
2个回答
推荐于2018-05-04
展开全部
java swing中利用JFormattedTextField的控件加keyReleased能实现,以下实现的只能输入数字的文本框代码:
import java.text.ParseException;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* @author Administrator
*/
public class JFormattedText extends JFrame {
private JFormattedTextField text;
public JFormattedText() {
JPanel panel = new JPanel();
text = new JFormattedTextField(new java.text.DecimalFormat("#0"));
// text = new JFormattedTextField();
// text.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
text.setFont(new java.awt.Font("宋体", 0, 12)); // NOI18N
text.setMaximumSize(new java.awt.Dimension(50, 21));
text.setMinimumSize(new java.awt.Dimension(50, 21));
text.setPreferredSize(new java.awt.Dimension(50, 21));
//过滤输入的字符
text.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
String old = text.getText();
JFormattedTextField.AbstractFormatter formatter = text.getFormatter();
if (!old.equals("")) {
if (formatter != null) {
String str = text.getText();
try {
long page = (Long) formatter.stringToValue(str);
text.setText(page + "");
} catch (ParseException pe) {
text.setText("1");//解析异常直接将文本框中值设置为1
}
}
}
}
});
panel.add(text);
this.add(panel);
this.setBounds(200, 100, 100, 100);
}
public static void main(String[] arg) {
new JFormattedText().setVisible(true);
}
}
import java.text.ParseException;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* @author Administrator
*/
public class JFormattedText extends JFrame {
private JFormattedTextField text;
public JFormattedText() {
JPanel panel = new JPanel();
text = new JFormattedTextField(new java.text.DecimalFormat("#0"));
// text = new JFormattedTextField();
// text.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
text.setFont(new java.awt.Font("宋体", 0, 12)); // NOI18N
text.setMaximumSize(new java.awt.Dimension(50, 21));
text.setMinimumSize(new java.awt.Dimension(50, 21));
text.setPreferredSize(new java.awt.Dimension(50, 21));
//过滤输入的字符
text.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
String old = text.getText();
JFormattedTextField.AbstractFormatter formatter = text.getFormatter();
if (!old.equals("")) {
if (formatter != null) {
String str = text.getText();
try {
long page = (Long) formatter.stringToValue(str);
text.setText(page + "");
} catch (ParseException pe) {
text.setText("1");//解析异常直接将文本框中值设置为1
}
}
}
}
});
panel.add(text);
this.add(panel);
this.setBounds(200, 100, 100, 100);
}
public static void main(String[] arg) {
new JFormattedText().setVisible(true);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询