国产gaysexchina男同gay,japanrcep老熟妇乱子伦视频,吃奶呻吟打开双腿做受动态图,成人色网站,国产av一区二区三区最新精品

App下載
首頁javajformattedtextfieldJava Swing - 如何為JFormattedTextField創(chuàng)建自定義java.text.Format

Java Swing - 如何為JFormattedTextField創(chuàng)建自定義java.text.Format

我們想知道如何為JFormattedTextField創(chuàng)建自定義java.text.Format。
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.text.MaskFormatter;
import java.awt.FlowLayout;
import java.text.AttributedCharacterIterator;
import java.text.FieldPosition;
import java.text.Format;
import java.text.NumberFormat;
import java.text.ParsePosition;

public class Main {
  public static void main(String[] args) throws Exception {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(100, 75);
    JPanel content = new JPanel(new FlowLayout());
    frame.setContentPane(content);

    MaskFormatter formatter = new MaskFormatter("#");
    formatter.setValidCharacters("123456789");

    JFormattedTextField f1 = new JFormattedTextField(formatter);
    f1.setValue(null);
    f1.setColumns(1);

    content.add(f1);
    frame.setVisible(true);
  }

  private static Format createFormat() {
    NumberFormat format = NumberFormat.getInstance();
    format.setParseIntegerOnly(true);
    return new Format() {
      @Override
      public StringBuffer format(Object obj, StringBuffer toAppendTo,
          FieldPosition pos) {
        return format.format(obj, toAppendTo, pos);
      }

      @Override
      public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
        return format.formatToCharacterIterator(obj);
      }

      @Override
      public Object parseObject(String source, ParsePosition pos) {
        int initialIndex = pos.getIndex();
        Object result = format.parseObject(source, pos);
        if (result != null && pos.getIndex() > initialIndex + 1) {
          int errorIndex = initialIndex + 1;
          pos.setIndex(initialIndex);
          pos.setErrorIndex(errorIndex);
          return null;
        }
        return result;
      }
    };
  }
}