Java 类javax.swing.text.MaskFormatter 实例源码

项目:incubator-netbeans    文件:FormatSelector.java   
/**
 * Returns format's pattern. 
 * 
 * @return format's pattern.
 */
public String getFormat() {
    if (format != null) return format;
    String fmt = null;
    if (formatter instanceof MaskFormatter) {
        fmt = ((MaskFormatter)formatter).getMask();
    } else if (formatter instanceof InternationalFormatter) {
        Format f = ((InternationalFormatter)formatter).getFormat();
        if (f instanceof DecimalFormat) {
            fmt = ((DecimalFormat)f).toPattern();
        } else if (f instanceof SimpleDateFormat) {
            fmt = ((SimpleDateFormat)f).toPattern();
        }
    }
    return fmt;
}
项目:cuba    文件:DesktopTimeField.java   
public DesktopTimeField() {
    UserSessionSource uss = AppBeans.get(UserSessionSource.NAME);

    digitWidth = getDigitWidth();

    timeFormat = Datatypes.getFormatStringsNN(uss.getLocale()).getTimeFormat();
    resolution = DateField.Resolution.MIN;
    formatter = new MaskFormatter();
    formatter.setPlaceholderCharacter('_');
    impl = new FlushableFormattedTextField(formatter);
    FieldListener listener = new FieldListener();
    impl.addFocusListener(listener);
    impl.addKeyListener(listener);

    setShowSeconds(timeFormat.contains("ss"));
}
项目:osdq-core    文件:FormatCheck.java   
public static Object parseString(String value, Object[] pattern) {
    MaskFormatter format = new MaskFormatter();
    format.setValueContainsLiteralCharacters(false);
    Object d = null;

    for (int i = 0; i < pattern.length; i++) {
        try {
            format.setMask(pattern[i].toString());
            d = format.stringToValue(value);
            if (d != null)
                break;
        } catch (Exception e) {
            continue;
        }
    } // End of for loop
    return d;
}
项目:invesdwin-nowicket    文件:FormInput.java   
/**
 * Instead of using the MaskConverter in the Page, we just validate the value here with a custom validator.
 */
public String validateUsPhoneNumber(final String newValue) {
    try {
        final MaskFormatter maskFormatter = new MaskFormatter("(###) ###-####");
        maskFormatter.setValueClass(String.class);
        maskFormatter.setAllowsInvalid(true);
        maskFormatter.setValueContainsLiteralCharacters(true);
        final Object obj = maskFormatter.stringToValue(newValue);
        if (obj != null) {
            return null;
        }
    } catch (final ParseException e) {
        //ignore
    }
    //so we can provide a different message than "is not a valid string"
    return "does not match the mask";
}
项目:cooper    文件:AddIPDialog.java   
public AddIPDialog(JDependCooper frame) throws ParseException {
    super();
    this.frame = frame;

    setSize(250, 100);
    this.setLocationRelativeTo(null);// 窗口在屏幕中间显示

    this.setLayout(new BorderLayout());

    MaskFormatter ipmask = new MaskFormatter("###.###.###.###");
    ipmask.setPlaceholderCharacter(' ');
    field = new JFormattedTextField(ipmask);
    field.setFont(new Font("Courier", Font.PLAIN, 18));
    field.setColumns(16);
    this.add(BorderLayout.CENTER, field);

    JPanel buttonPanel = new JPanel();
    buttonPanel.add(this.createOkButton());
    buttonPanel.add(this.createCloseButton());

    this.add(BorderLayout.SOUTH, buttonPanel);

}
项目:Sudoku-Solver    文件:SudokuSolver.java   
private void createGridFields() {
   mGrid = new JFormattedTextField[9][];
   for(int i = 0; i < 9; i++) {
      mGrid[i] = new JFormattedTextField[9];
      for(int j = 0; j < 9; j++) {
           try {
              mGrid[i][j] = new JFormattedTextField(new MaskFormatter("#"));
           }
           catch (ParseException ex) {
                System.err.println("ParseException while creating grid.");
              System.exit(1);
           }
           mGrid[i][j].setHorizontalAlignment(JFormattedTextField.CENTER);
           mGrid[i][j].setForeground(Color.BLACK);
           mGrid[i][j].addKeyListener(getGridKeyAdapter(i, j));
           mGrid[i][j].addMouseListener(getGridMouseAdapter(mGrid[i][j]));
      }
   }
}
项目:Cine-Movies    文件:Formatacoes.java   
/** Inicializa os campos */
protected Formatacoes()
{
    try {
        cpf = new MaskFormatter("###.###.###-##");
        cpf.setPlaceholderCharacter('_');
        rg = new MaskFormatter("#########");
        rg.setPlaceholderCharacter('_');
        telefone = new MaskFormatter("####-####");
        telefone.setPlaceholderCharacter('_');
        telefone2 = new MaskFormatter("####-####");
        telefone2.setPlaceholderCharacter('_');
        data = new MaskFormatter("##/##/####");
        data.setPlaceholderCharacter('_');
        cep = new MaskFormatter("#####-###");
        cep.setPlaceholderCharacter('_');
        tipo = new MaskFormatter("U");
        tipo.setPlaceholder(" ");
        tipo.setValidCharacters("CFA");
    } catch (ParseException e) {
        JOptionPane.showMessageDialog(null,"ERRO: N�o foi poss�vel criar as m�scaras dos campos da janela.");
    }
}
项目:fll-sw    文件:ScheduleDurationField.java   
/**
 * @param value the duration to use for the initial value, may not be null
 */
public ScheduleDurationField(final Duration value) {
  setInputVerifier(new TimeVerifier());

  try {
    final MaskFormatter mf = new MaskFormatter(MASKFORMAT);
    mf.setPlaceholderCharacter('_');
    mf.setValueClass(String.class);
    final DefaultFormatterFactory dff = new DefaultFormatterFactory(mf);
    setFormatterFactory(dff);
  } catch (final ParseException pe) {
    throw new FLLInternalException("Invalid format for MaskFormatter", pe);
  }

  setDuration(value);
}
项目:wichtel    文件:FormatFactory.java   
/**
 * Creates a {@link MaskFormatter} from a given pattern.
 *
 * @param format for the formatter
 * @return created {@link MaskFormatter}
 * @throws ParseException
 * @see MaskFormatter
 * @since 0.0.1
 */
public static MaskFormatter createMaskFormatter(final String format) throws ParseException {
    if (log.isDebugEnabled()) log.debug(HelperLog.methodStart(format));
    if (null == format) {
        throw new RuntimeExceptionIsNull("format"); //$NON-NLS-1$
    }

    final MaskFormatter result = new MaskFormatter(format) {
        private static final long serialVersionUID = 5212947957420446007L;

        {
            setCommitsOnValidEdit(true);
            setPlaceholderCharacter('_');
        }
    };

    if (log.isDebugEnabled()) log.debug(HelperLog.methodExit(result));
    return result;
}
项目:kkMulticopterFlashTool    文件:JNamedIntMenuItem.java   
private void init() {
    //create the CellContraints
    cc  = new CellConstraints();

    // create the Layout for Panel this
    String panelColumns = "pref,3dlu,fill:pref:grow";
    String panelRows = "pref";
    FormLayout panelLayout = new FormLayout(panelColumns, panelRows);
    this.setLayout(panelLayout);

    this.marker = new JLabel(label+":");
    this.valueField = new JFormattedTextField();
    if (this.valueField.getBackground().equals(Color.BLACK)) {
        this.valueField.setBackground(Color.WHITE);
    }

    try {
            mf = new MaskFormatter ("##");
    } catch (java.text.ParseException e) {

    }
    javax.swing.text.DefaultFormatterFactory dff = new  DefaultFormatterFactory(mf);
    valueField.setFormatterFactory(dff);
    valueField.addFocusListener(listener);

    this.add(marker, cc.xy(1, 1));
    this.add(valueField, cc.xy(3,1));
}
项目:tecnocar    文件:Rotinas.java   
public static String formatarString(String texto, String mascara) throws ParseException {
    MaskFormatter mf = new MaskFormatter(mascara);
    mf.setValueContainsLiteralCharacters(false);
    return mf.valueToString(texto);
}
项目:maps4cim    文件:FormattedComponents.java   
public static MaskFormatter getHexFormatter(int length) {
    try {
        return new MaskFormatter(Strings.repeat("H", length));
    } catch (ParseException e) {
        log.error("Error creating MaskFormatter", e);
        return null;
    }
}
项目:fll-sw    文件:ScheduleTimeField.java   
/**
 * @param value the initial value for the widget
 */
public ScheduleTimeField(final LocalTime value) {
  try {
    final MaskFormatter mf = new MaskFormatter(MASKFORMAT);
    mf.setPlaceholderCharacter('_');
    mf.setValueClass(String.class);
    final DefaultFormatterFactory dff = new DefaultFormatterFactory(mf);
    setFormatterFactory(dff);
  } catch (final ParseException pe) {
    throw new FLLInternalException("Invalid format for MaskFormatter", pe);
  }

  setTime(value);
}
项目:JavaExamples    文件:BirIslemApp.java   
/**
 * Grafiksel arayuz bilesenlerini olusturup pencereye ekleme isini yapan
 * metot
 */
private void initialize() {
    this.setSize(395, 110);
    this.setTitle("Bir İşlem");
    this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    this.getContentPane().setLayout(null);

    // Sayilar arayuze ekleniyor
    this.getContentPane().add(
            createLabel("SAYILAR:", new Rectangle(0, 0, 100, 25)));
    try {
        // Sadece iki basamak kabul eden bicimlendirici
        MaskFormatter ikiBasamak = new MaskFormatter("##");
        // Sadece uc basamak kabul eden bicimlendirici
        MaskFormatter ucBasamak = new MaskFormatter("###");

        // Metin alanlari bicimli metin alani olarak yaratiliyor
        // veri giris hatalarini onlemeye calisiyoruz
        txtSayi1 = new JFormattedTextField(ikiBasamak);
        txtSayi1.setBounds(new Rectangle(100, 0, 30, 25));
        this.getContentPane().add(txtSayi1);
        txtSayi2 = new JFormattedTextField(ikiBasamak);
        txtSayi2.setBounds(new Rectangle(130, 0, 30, 25));
        this.getContentPane().add(txtSayi2);
        txtSayi3 = new JFormattedTextField(ikiBasamak);
        txtSayi3.setBounds(new Rectangle(160, 0, 30, 25));
        this.getContentPane().add(txtSayi3);
        txtSayi4 = new JFormattedTextField(ikiBasamak);
        txtSayi4.setBounds(new Rectangle(190, 0, 30, 25));
        this.getContentPane().add(txtSayi4);
        txtSayi5 = new JFormattedTextField(ikiBasamak);
        txtSayi5.setBounds(new Rectangle(220, 0, 30, 25));
        this.getContentPane().add(txtSayi5);
        txtSayi6 = new JFormattedTextField(ucBasamak);
        txtSayi6.setBounds(new Rectangle(250, 0, 30, 25));
        this.getContentPane().add(txtSayi6);
        // Hedef Sayi arayuze ekleniyor
        this.getContentPane().add(
                createLabel("HEDEF SAYI:", new Rectangle(0, 25, 100, 25)));
        txtHedefSayi = new JFormattedTextField(ucBasamak);
        txtHedefSayi.setBounds(100, 25, 30, 25);
        this.getContentPane().add(txtHedefSayi);
        // Dugmeler ekleniyor
        this.getContentPane().add(getBtnRandomSayi());
        this.getContentPane().add(getBtnRandomHedefSayi());
        this.getContentPane().add(getBtnHesapla());
        // Sonuc ekleniyor
        lblCozum = new JLabel();
        lblCozum.setBounds(0, 50, 300, 25);
        this.getContentPane().add(lblCozum);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}
项目:eplmp    文件:Tools.java   
public static String increaseId(String id, String mask) throws ParseException {
    LOGGER.info("#### Tools.increaseId id = " + id + " , mask = " + mask);
    MaskFormatter formatter = new MaskFormatter(mask);
    formatter.setValueContainsLiteralCharacters(false);
    String value = formatter.stringToValue(id).toString();
    StringBuilder newValue = new StringBuilder();
    boolean increase = true;
    for (int i = value.length() - 1; i >= 0; i--) {
        char c = value.charAt(i);
        switch (c) {
            case '9':
                newValue.append((increase) ? '0' : '9');
                break;

            case '8':
                newValue.append((increase) ? '9' : '8');
                increase = false;
                break;

            case '7':
                newValue.append((increase) ? '8' : '7');
                increase = false;
                break;

            case '6':
                newValue.append((increase) ? '7' : '6');
                increase = false;
                break;

            case '5':
                newValue.append((increase) ? '6' : '5');
                increase = false;
                break;

            case '4':
                newValue.append((increase) ? '5' : '4');
                increase = false;
                break;

            case '3':
                newValue.append((increase) ? '4' : '3');
                increase = false;
                break;

            case '2':
                newValue.append((increase) ? '3' : '2');
                increase = false;
                break;

            case '1':
                newValue.append((increase) ? '2' : '1');
                increase = false;
                break;

            case '0':
                newValue.append((increase) ? '1' : '0');
                increase = false;
                break;

            default:
                newValue.append(c);
                break;
        }
    }
    return formatter.valueToString(newValue.reverse().toString());
}
项目:cuba    文件:DesktopTimeField.java   
public FlushableFormattedTextField(MaskFormatter formatter) {
    super(formatter);
}
项目:JGrafix    文件:Utils.java   
public static void setFormatterFactory(JFormattedTextField componente,
    String mascara) throws ParseException {
  componente.setFormatterFactory(new DefaultFormatterFactory(
    new MaskFormatter(mascara)));
}
项目:logisim-evolution    文件:Pin.java   
public EditText(Value value, RadixOption radix, int width) {
    super();
    String mask = "";
    GridBagConstraints gbc = new GridBagConstraints();
    MaskFormatter formatter = new MaskFormatter();
    DecimalFormat df = new DecimalFormat();
    JLabel label = new JLabel("");
    Color back = new Color(0xff, 0xf0, 0x99);

    setUndecorated(true);
    setModal(true);
    setLayout(new GridBagLayout());

    this.radix = radix;
    bitWidth = width;
    oldVal = value;
    // System.err.println("Wdth:"+bitWidth);

    try {
        formatter.setPlaceholderCharacter('_');
        if (radix == RadixOption.RADIX_16) {
            label.setText("0x");
            for (int i = 0; i < Math.ceil(bitWidth / 4.0); i++) {
                mask += "H";
            }
            formatter.setMask(mask);
            text = new JFormattedTextField(formatter);
            text.setText(value.toHexString());
        } else if (radix == RadixOption.RADIX_8) {
            label.setText("0");
            for (int i = 0; i < Math.ceil(bitWidth / 3.0); i++) {
                mask += "#";
            }
            formatter.setInvalidCharacters("89");
            formatter.setMask(mask);
            text = new JFormattedTextField(formatter);
            text.setText(value.toOctalString());
        } else if (radix == RadixOption.RADIX_10_SIGNED) {
            mask = "#;-#";
            df.setParseIntegerOnly(true);
            df.applyPattern(mask);
            df.setMaximumIntegerDigits(11);
            text = new JFormattedTextField(df);
            text.setColumns(11);
            // System.err.println("Val:" + value.toDecimalString(true));
            text.setText(value.toDecimalString(true));
        } else if (radix == RadixOption.RADIX_10_UNSIGNED) {
            mask = "#;";
            df.setParseIntegerOnly(true);
            df.applyPattern(mask);
            df.setMaximumIntegerDigits(10);
            text = new JFormattedTextField(df);
            text.setColumns(10);
            // System.err.println("Val:" +
            // value.toDecimalString(false));
            text.setText(value.toDecimalString(false));
        }
    } catch (ParseException ex) {
        Logger.getLogger(Pin.class.getName()).log(Level.SEVERE, null,
                ex);
    }

    gbc.gridx = gbc.gridy = 0;
    add(label, gbc);
    gbc.gridx = 1;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.anchor = GridBagConstraints.BASELINE;
    text.addKeyListener(this);
    text.setBorder(null);
    text.setBackground(back);
    add(text, gbc);

    pack();
}
项目:Cine-Movies    文件:Formatacoes.java   
/**
 * @return the cpf
 */
public MaskFormatter getCpf() {
    return cpf;
}
项目:Cine-Movies    文件:Formatacoes.java   
/**
 * @return the rg
 */
public MaskFormatter getRg() {
    return rg;
}
项目:Cine-Movies    文件:Formatacoes.java   
/**
 * @return the telefone
 */
public MaskFormatter getTelefone2() {
    return telefone2;
}
项目:Cine-Movies    文件:Formatacoes.java   
/**
 * @return the telefone
 */
public MaskFormatter getTelefone() {
    return telefone;
}
项目:Cine-Movies    文件:Formatacoes.java   
/**
 * @return the data
 */
public MaskFormatter getData() {
    return data;
}
项目:Cine-Movies    文件:Formatacoes.java   
/**
 * @return the cep
 */
public MaskFormatter getCep() {
    return cep;
}
项目:Cine-Movies    文件:Formatacoes.java   
/**
 * @return the tipo
 */
public MaskFormatter getTipo() {
    return tipo;
}
项目:WBS-Project    文件:AddWorkEffortView.java   
/**
 * Main-Frame bekommt den Namen "WPAufwand" zugewiesen es wird das
 * Windows Look and Feel verwendet die verschiedenen Menüs, Buttons
 * etc. werden initialisiert und zu dem GridBagLayout hinzugefügt und
 * angeordnet mittels createGbc
 */
public AddWorkEffortView(final ActionsDelegate delegate) {
    super();

    this.actionsDelegate = delegate;

    initialize();
    setResizable(false);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    Wbs wbsStrings = LocalizedStrings.getWbs();
    Button buttonStrings = LocalizedStrings.getButton();

    lblID = new JLabel(wbsStrings.workPackageId());
    txfNr = new FilterJTextField();
    txfNr.setEnabled(false);

    lblName = new JLabel(wbsStrings.workPackageName());
    txfName = new FilterJTextField();
    txfName.setEnabled(false);

    lblUser = new JLabel(LocalizedStrings.getLogin().user());
    cobUser = new JComboBox<Worker>();

    lblBeschreibung = new JLabel(LocalizedStrings.getGeneralStrings()
        .description());
    txfBeschreibung = new FilterJTextField();

    lblAufwandZeit = new JLabel(wbsStrings.workEffortTime());
    cobAufwandZeit = new JComboBox<>(strAufwandZeit);

    lblAufwand = new JLabel(wbsStrings.workEffort());
    txfAufwand = new FilterJTextField();

    lblDatum = new JLabel(LocalizedStrings.getGeneralStrings().date());
    // Textfeld Datum bekommt das Format dd.mm.yyyy und hat das
    // aktuelle Datum drinnen stehen
    try {
        txfDatum = new JFormattedTextField(new MaskFormatter(
            "##.##.####"));
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
        String str = dateFormat.format(new Date());
        txfDatum.setText(str);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    btnOk = new JButton(buttonStrings.ok());
    btnCancel = new JButton(buttonStrings.cancel());

    createGBC(lblID, 0, 0, 1, 1);
    createGBC(txfNr, 1, 0, 1, 1);
    createGBC(lblName, 0, 1, 1, 1);
    createGBC(txfName, 1, 1, 1, 1);
    createGBC(lblUser, 0, 2, 1, 1);
    createGBC(cobUser, 1, 2, 1, 1);
    createGBC(lblBeschreibung, 0, 3, 1, 1);
    createGBC(txfBeschreibung, 1, 3, 1, 1);
    createGBC(lblAufwandZeit,0,4,1,1);
    createGBC(cobAufwandZeit,1,4,1,1);
    createGBC(lblAufwand, 0, 5, 1, 1);
    createGBC(txfAufwand, 1, 5, 1, 1);
    createGBC(lblDatum, 0, 6, 1, 1);
    createGBC(txfDatum, 1, 6, 1, 1);
    createGBC(btnOk, 0, 7, 1, 1);
    createGBC(btnCancel, 1, 7, 1, 1);

    addActionListeners();

    setVisible(true);


}