package com.laozhao.msas.util; import java.awt.Toolkit; import java.util.regex.Pattern; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; /** * * 数字输入框 number(precision,scale) precision:1~38 scale:0~127 * * @author LaoZhao * */ public class NumberFile extends JTextField { /** * */ private static final long serialVersionUID = 7766646453110003951L; private int precision = 8; private int scale = 0; private final Pattern intp = Pattern.compile("\\d+"); private Pattern dicp = Pattern.compile("\\d{1," + (precision - scale) + "}[.]{1}\\d{0," + scale + "}"); public int getPrecision() { return precision; } public int getScale() { return scale; } public NumberFile() { super(); setDocument(new NumberDocument()); } public NumberFile(int precision, int scale) { super(); setScale(precision, scale); setDocument(new NumberDocument()); } public void setScale(int precision, int scale) { this.precision = precision; this.scale = scale; if (precision < 1 || precision > 38) { throw new java.lang.IllegalArgumentException( "precision must letter than 38 and bigger than 1"); } else if (scale < -1 || scale > 127) { throw new java.lang.IllegalArgumentException( "scale must letter than 127 and bigger than -1"); } else if (precision <= scale) { throw new java.lang.IllegalArgumentException( "precision must bigger than scale"); } else { dicp = Pattern.compile("\\d{1," + (precision - scale) + "}[.]{1}\\d{0," + scale + "}"); } } public Integer getIntValue() { return getDoubleValue().intValue(); } public Double getDoubleValue() { return Double.parseDouble(getText()); } class NumberDocument extends PlainDocument { /** * */ private static final long serialVersionUID = 618631385104970883L; public NumberDocument() { super(); } public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { try { System.out.println(str); if (offs < precision - scale) { if (!intp.matcher(getText(0, getLength()) + str).matches()) { return; } } else { if (!dicp.matcher(getText(0, getLength()) + str).matches()) { return; } } super.insertString(offs, str, a); } catch (Exception e) { Toolkit.getDefaultToolkit().beep(); } } } public static void main(String[] args) { JFrame frame = new JFrame(); NumberFile nun = new NumberFile(8, 3); frame.add(nun); nun.setScale(5, 2); frame.setVisible(true); frame.pack(); } }
NumberFile 数字输入框
最近写了一个小程序,需要用到数字输入框,感觉这个东西大家都在用,但是竟然没有找到一个控件,比较郁闷,所以就自己写了一个,大家可以分享一下。欢迎使用,欢迎提意见。
猜你喜欢
转载自laozhao.iteye.com/blog/1629161
今日推荐
周排行