不管插入符号位于何处,这都迫使用户始终从右侧输入文本。插入新字符后,所有先前的字符都会向左移动。格式化将根据您的格式化程序应用:
import java.awt.*;import java.text.*;import javax.swing.*;import javax.swing.text.*;public class ABMTextField extends JTextField{ private DecimalFormat format; private String decimal; public ABMTextField(DecimalFormat format) { this.format = format; decimal = Character.toString( format.getDecimalFormatSymbols().getDecimalSeparator() ); setColumns( format.toPattern().length() ); setHorizontalAlignment(JFormattedTextField.TRAILING); setText( format.format(0.0) ); Abstractdocument doc = (Abstractdocument)getdocument(); doc.setdocumentFilter( new ABMFilter() ); } @Override public void setText(String text) { Number number = format.parse(text, new ParsePosition(0)); if (number != null) super.setText( text ); } public class ABMFilter extends documentFilter { public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException { replace(fb, offs, 0, str, a); } public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException { if ("0123456789".contains(str)) { document doc = fb.getdocument(); StringBuilder sb = new StringBuilder( doc.getText(0, doc.getLength()) ); int decimalOffset = sb.indexOf( decimal ); if (decimalOffset != -1) { sb.deleteCharAt(decimalOffset); sb.insert(decimalOffset + 1, decimal); } sb.append(str); try { String text = format.format( format.parse( sb.toString() ) ); super.replace(fb, 0, doc.getLength(), text, a); } catch(ParseException e) {} } else Toolkit.getDefaultToolkit().beep(); } public void remove(documentFilter.FilterBypass fb, int offset, int length) throws BadLocationException { document doc = fb.getdocument(); StringBuilder sb = new StringBuilder( doc.getText(0, doc.getLength()) ); int decimalOffset = sb.indexOf( decimal ); if (decimalOffset != -1) { sb.deleteCharAt(decimalOffset); sb.insert(decimalOffset - 1, decimal); } sb.deleteCharAt( sb.length() - 1) ; try { String text = format.format( format.parse( sb.toString() ) ); super.replace(fb, 0, doc.getLength(), text, null); } catch(ParseException e) {} } } private static void createAndShowUI() { DecimalFormat format = new DecimalFormat("###,##0.00"); ABMTextField abm = new ABMTextField( format ); JPanel panel = new JPanel(); panel.add( abm ); Jframe frame = new Jframe("ABMTextField"); frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); frame.add( panel ); frame.setSize(200, 200); frame.setLocationByPlatform( true ); frame.setVisible( true ); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { createAndShowUI(); } }); }}如果我想使用该字符串进行计算,该如何返回给我?
您将需要创建一个方法,也许是使用format.parse(…)方法返回实际数字的getValue()。



