JTextField只能输入数字与小数位数的控制

本文介绍了一种使用Java实现的JTextField组件,该组件仅允许输入数字,并能有效控制输入的数字的小数位数与总长度。通过自定义文档验证机制,确保了输入数据的格式符合需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现JTextField只能输入数字,并且控制小数的位数与数字的总长度

 

import java.awt.Container;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.math.BigDecimal;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 * 只能输入数字
 * @author 心星
 */
public class Txtonlynumber {

	public Txtonlynumber() {
		JFrame f = new JFrame("Txtonlynumber");
		Container contentPane = f.getContentPane();
		JTextField salary = new JTextField(50);
		salary.setDocument(new NumOnlyDocument());

		contentPane.add(salary);
		f.pack();
		f.setVisible(true);
		f.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
	}

	public static void main(String[] args) {
		new Txtonlynumber();

	}

	class NumOnlyDocument extends PlainDocument {
		private static final long serialVersionUID = 1001689415662878505L;
		
		int maxLen;  //最长字符长度
		int decimalLen; //小数位数
		
		public NumOnlyDocument() {
			this(2,13);
		}
		
		public NumOnlyDocument(int newDecimalLen, int newMaxLen) {
			super();
			decimalLen = newDecimalLen;
			maxLen = newMaxLen;
		}
		
		public void insertString(int offset, String inStr, AttributeSet attrSet) 
			throws BadLocationException {
			// 获得输入框有效值
			String numStr = getText(0, offset) + inStr + getText(offset, getLength() - offset);
			System.out.println("inStr===" + inStr + ",offset==" + offset 
				+ ",getLength()=" + getLength() + ",value=" + numStr);
			// 校验字符长度限制
			if (getLength() + inStr.length() > maxLen) {
				return;
			}
			// 校验是否是有效数字
			try {
				new BigDecimal(numStr);
			} catch (NumberFormatException e1) {
				return;
			}
			// 校验小数位数限制
			int indexNum = numStr.indexOf(".");
			if (indexNum > 0) {
				int len = numStr.substring(indexNum + 1).length();
				if (len > decimalLen) {
					return;
				}
			}
			super.insertString(offset, inStr, attrSet);
		}
	}

}

 

 

 

 

import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class TemperatureConverter { public static void main(String[] args) { // 创建并显示GUI SwingUtilities.invokeLater(new Runnable() { public void run() { new TemperatureConverterFrame(); } }); } } class TemperatureConverterFrame extends JFrame { private JTextField inputField; private JButton celsiusButton, fahrenheitButton; private JLabel resultLabel; public TemperatureConverterFrame() { // 设置窗口标题和大小 setTitle("温度转换器"); setSize(400, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); // 居中显示 // 初始化组件 inputField = new JTextField(10); celsiusButton = new JButton("转换为摄氏度"); fahrenheitButton = new JButton("转换为华氏度"); resultLabel = new JLabel("结果: "); // 布局设置 JPanel panel = new JPanel(); panel.add(new JLabel("输入温度:")); panel.add(inputField); panel.add(celsiusButton); panel.add(fahrenheitButton); panel.add(resultLabel); add(panel); // 添加按钮事件监听器 celsiusButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { convertToCelsius(); } }); fahrenheitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { convertToFahrenheit(); } }); // 显示窗口 setVisible(true); } // 摄氏度转换方法 private void convertToCelsius() { try { double fahrenheit = Double.parseDouble(inputField.getText()); double celsius = (fahrenheit - 32) * 5 / 9; resultLabel.setText("结果: " + String.format("%.2f", celsius) + "°C"); } catch (NumberFormatException ex) { resultLabel.setText("请输入有效的数字"); } } // 华氏度转换方法 private void convertToFahrenheit() { try { double celsius = Double.parseDouble(inputField.getText()); double fahrenheit = celsius * 9 / 5 + 32; resultLabel.setText("结果: " + String.format("%.2f", fahrenheit) + "°F"); } catch (NumberFormatException ex) { resultLabel.setText("请输入有效的数字"); } } }优化此代码
06-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值