java 从swing界面获取数字_Java Swing - 如何只接受自定义JTextField中的数字

本文介绍如何在Java Swing应用中创建一个JTextField,只允许用户输入数字。通过自定义JTextField的PlainDocument类实现字符过滤,确保输入的字符仅限于0-9。示例代码展示了如何设置和使用这个过滤器。
摘要由CSDN通过智能技术生成

import java.awt.FlowLayout;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JTextField;

import javax.swing.text.AttributeSet;

import javax.swing.text.BadLocationException;

import javax.swing.text.PlainDocument;

class JTextFieldFilter extends PlainDocument {

public static final String NUMERIC = "0123456789";

protected String acceptedChars = null;

protected boolean negativeAccepted = false;

public JTextFieldFilter() {

this(NUMERIC);

}

public JTextFieldFilter(String acceptedchars) {

acceptedChars = acceptedchars;

}

public void setNegativeAccepted(boolean negativeaccepted) {

if (acceptedChars.equals(NUMERIC)) {

negativeAccepted = negativeaccepted;

acceptedChars += "-";

}

}

public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {

if (str == null)

return;

for (int i = 0; i < str.length(); i++) {

if (acceptedChars.indexOf(str.valueOf(str.charAt(i))) == -1)

return;

}

if (negativeAccepted && str.indexOf("-") != -1) {

if (str.indexOf("-") != 0 || offset != 0) {

return;

}

}

super.insertString(offset, str, attr);

}

}

public class Main extends JFrame{

public static void main(String[] argv) throws Exception {

new Main();

}

public Main() {

JTextField tf1, tf1b, tf1c, tf2, tf3;

JLabel l1, l1b, l1c, l2, l3;

setLayout(new FlowLayout());

//

l1 = new JLabel("only numerics");

tf1 = new JTextField(10);

getContentPane().add(l1);

getContentPane().add(tf1);

tf1.setDocument(new JTextFieldFilter(JTextFieldFilter.NUMERIC));

setSize(300,300);

setVisible(true);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值