Java Code Examples for javax.swing.text.MaskFormatter

The following are top voted examples for showing how to use javax.swing.text.MaskFormatter. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: FormatSelector.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 2
Project: cuba   File: DesktopTimeField.java   Source Code and License 6 votes vote down vote up
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"));
}
 
Example 3
Project: osdq-core   File: FormatCheck.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 4
Project: invesdwin-nowicket   File: FormInput.java   Source Code and License 6 votes vote down vote up
/**
 * 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";
}
 
Example 5
Project: cooper   File: AddIPDialog.java   Source Code and License 6 votes vote down vote up
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);

}
 
Example 6
Project: Sudoku-Solver   File: SudokuSolver.java   Source Code and License 6 votes vote down vote up
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]));
      }
   }
}
 
Example 7
Project: fll-sw   File: ScheduleDurationField.java   Source Code and License 6 votes vote down vote up
/**
 * @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);
}
 
Example 8
Project: wichtel   File: FormatFactory.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 9
Project: kkMulticopterFlashTool   File: JNamedIntMenuItem.java   Source Code and License 5 votes vote down vote up
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));
}
 
Example 10
Project: tecnocar   File: Rotinas.java   Source Code and License 5 votes vote down vote up
public static String formatarString(String texto, String mascara) throws ParseException {
    MaskFormatter mf = new MaskFormatter(mascara);
    mf.setValueContainsLiteralCharacters(false);
    return mf.valueToString(texto);
}
 
Example 11
Project: maps4cim   File: FormattedComponents.java   Source Code and License 5 votes vote down vote up
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;
    }
}
 
Example 12
Project: fll-sw   File: ScheduleTimeField.java   Source Code and License 5 votes vote down vote up
/**
 * @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);
}
 
Example 13
Project: JavaExamples   File: BirIslemApp.java   Source Code and License 4 votes vote down vote up
/**
 * 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);
    }

}
 
Example 14
Project: eplmp   File: Tools.java   Source Code and License 4 votes vote down vote up
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());
}
 
Example 15
Project: cuba   File: DesktopTimeField.java   Source Code and License 4 votes vote down vote up
public FlushableFormattedTextField(MaskFormatter formatter) {
    super(formatter);
}
 
Example 16
Project: JGrafix   File: Utils.java   Source Code and License 4 votes vote down vote up
public static void setFormatterFactory(JFormattedTextField componente,
    String mascara) throws ParseException {
  componente.setFormatterFactory(new DefaultFormatterFactory(
    new MaskFormatter(mascara)));
}
 
Example 17
Project: logisim-evolution   File: Pin.java   Source Code and License 4 votes vote down vote up
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();
}
 
Example 18
Project: Cine-Movies   File: Formatacoes.java   Source Code and License 4 votes vote down vote up
/** 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.");
	}
}
 
Example 19
Project: Cine-Movies   File: Formatacoes.java   Source Code and License 4 votes vote down vote up
/**
 * @return the cpf
 */
public MaskFormatter getCpf() {
	return cpf;
}
 
Example 20
Project: Cine-Movies   File: Formatacoes.java   Source Code and License 4 votes vote down vote up
/**
 * @return the rg
 */
public MaskFormatter getRg() {
	return rg;
}
 
Example 21
Project: Cine-Movies   File: Formatacoes.java   Source Code and License 4 votes vote down vote up
/**
 * @return the telefone
 */
public MaskFormatter getTelefone2() {
	return telefone2;
}
 
Example 22
Project: Cine-Movies   File: Formatacoes.java   Source Code and License 4 votes vote down vote up
/**
 * @return the telefone
 */
public MaskFormatter getTelefone() {
	return telefone;
}
 
Example 23
Project: Cine-Movies   File: Formatacoes.java   Source Code and License 4 votes vote down vote up
/**
 * @return the data
 */
public MaskFormatter getData() {
	return data;
}
 
Example 24
Project: Cine-Movies   File: Formatacoes.java   Source Code and License 4 votes vote down vote up
/**
 * @return the cep
 */
public MaskFormatter getCep() {
	return cep;
}
 
Example 25
Project: Cine-Movies   File: Formatacoes.java   Source Code and License 4 votes vote down vote up
/**
 * @return the tipo
 */
public MaskFormatter getTipo() {
	return tipo;
}
 
Example 26
Project: WBS-Project   File: AddWorkEffortView.java   Source Code and License 4 votes vote down vote up
/**
 * 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);


}