forked from fanruan/design
xiqiu
3 years ago
18 changed files with 1062 additions and 795 deletions
@ -0,0 +1,76 @@
|
||||
package com.fr.design.gui.itextfield; |
||||
|
||||
import javax.swing.text.AttributeSet; |
||||
import javax.swing.text.BadLocationException; |
||||
import javax.swing.text.PlainDocument; |
||||
import java.awt.Toolkit; |
||||
|
||||
public class UIPositiveAndNegativeIntNumberField extends UINumberField { |
||||
private static final long serialVersionUID = 4946379346015964509L; |
||||
|
||||
public void setFieldDocument() { |
||||
setDocument(createNumberDocument()); |
||||
} |
||||
|
||||
public class NumberDocument extends PlainDocument { |
||||
private static final long serialVersionUID = 1024213269275179172L; |
||||
|
||||
public NumberDocument() { |
||||
} |
||||
|
||||
public boolean checkString(int offset, String s, String str) { |
||||
String strNew = str.substring(0, offset) + s + str.substring(offset, getLength()); |
||||
return isMinusSignOnly(strNew) || (isIntNumber(strNew) && isInputIllegalNumber(strNew) && !isOverMaxOrMinValue(strNew)); |
||||
|
||||
} |
||||
|
||||
public void insertString(int offset, String s, AttributeSet a) throws BadLocationException { |
||||
String str = getText(0, getLength()); |
||||
if (!checkString(offset, s, str)) { |
||||
Toolkit.getDefaultToolkit().beep(); |
||||
return; |
||||
} |
||||
|
||||
setisContentChanged(true); |
||||
super.insertString(offset, s, a); |
||||
} |
||||
|
||||
private boolean isMinusSignOnly(String s) { |
||||
return s.contains("-") && s.length() == 1; |
||||
} |
||||
|
||||
/** |
||||
* 输入字符是否是不合法数字 |
||||
* @param s 输入的字符串 |
||||
* @return 是否不合法 |
||||
*/ |
||||
private boolean isInputIllegalNumber(String s) { |
||||
try { |
||||
Integer.parseInt(s); |
||||
} catch (Exception e) { |
||||
return false; |
||||
} |
||||
return true; |
||||
} |
||||
|
||||
private boolean isIntNumber(String s) { |
||||
boolean result = true; |
||||
for (int i = 0; i < s.length(); i++) { |
||||
String ch = s.charAt(i) + ""; |
||||
if (!ch.matches("^[0-9\\-]+$")) { |
||||
result = false; |
||||
} |
||||
} |
||||
return result; |
||||
} |
||||
|
||||
private boolean isOverMaxOrMinValue(String s) { |
||||
int value = Integer.parseInt(s); |
||||
return (value < getMinValue() || value > getMaxValue()); |
||||
} |
||||
} |
||||
|
||||
public NumberDocument createNumberDocument() { |
||||
return new NumberDocument(); |
||||
} |
||||
} |
Loading…
Reference in new issue