Input: any number of hyphen-delimeted numbers. Output: int array : Formatted TextField « Swing JFC « Java

Input: any number of hyphen-delimeted numbers. Output: int array

Input: any number of hyphen-delimeted numbers. Output: int array
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O'Reilly 
//Input: string of form "15-45-22" (any number of hyphen-delimeted numbers)
//<br>Output: int array

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.text.DefaultFormatter;

public class CombinationFormatter extends DefaultFormatter {

  public CombinationFormatter() {

  public Object stringToValue(String string) throws java.text.ParseException {
    // input: string of form "15-45-22" (any number of hyphen-delimeted
    // numbers)
    // output: int array
    String s[] = string.split("-");
    int a[] = new int[s.length];
    for (int j = 0; j < a.length; j += 1)
      try {
        a[j] = Integer.parseInt(s[j]);
      } catch (NumberFormatException nfe) {
        throw new java.text.ParseException(s[j] + " is not an int", 0);
    return a;

  public String valueToString(Object value) throws java.text.ParseException {
    //  input: int array
    // output: string of numerals separated by hyphens
    if (value == null)
      return null;
    if (!(value instanceof int[]))
      throw new java.text.ParseException("expected int[]", 0);
    int a[] = (int[]) value;
    StringBuffer sb = new StringBuffer();
    for (int j = 0; j < a.length; j += 1) {
      if (j > 0)
    return sb.toString();

  protected Action[] getActions() {
    Action[] actions = { new CombinationIncrementer("increment", 1),
        new CombinationIncrementer("decrement", -1) };
    return actions;

  // begin inner class ----------------------------------------

  public class CombinationIncrementer extends AbstractAction {
    protected int delta;

    public CombinationIncrementer(String name, int delta) { // constructor
      super(name); // 'name' must match something in the component's
             // InputMap
      // or else this Action will not get invoked automatically.
      // Valid names include: "reset-field-edit", "increment",
      // "decrement", and "unselect" (see appendix B) = delta;

    public void actionPerformed(java.awt.event.ActionEvent ae) {
      JFormattedTextField ftf = getFormattedTextField(); // from
                                 // AbstractFormtter
      if (ftf == null)
      String text = ftf.getText();
      if (text == null)
      int pos = ftf.getCaretPosition();

      int hyphenCount = 0;
      for (int j = 0; j < pos; j += 1)
        // how many hyphens precede the caret?
        if (text.charAt(j) == '-')
          hyphenCount += 1;
      try {
        int a[] = (int[]) stringToValue(text);
        a[hyphenCount] += delta; // change the number at caret position
        if (a[hyphenCount] < 0)
          a[hyphenCount] = 0;
        String newText = valueToString(a);
        ftf.setText(newText); // does not retain caret position
        if ((text.charAt(pos) == '-')
            && (newText.length() < text.length()))
          pos -= 1; // don't let caret move past '-' when '10' changes
                // to '9'
      } catch (Exception e) {

  // end inner class ----------------------------------------

  public static void main(String argv[]) {
    // a demo main() to show how CombinationFormatter could be used
    int comb1[] = { 35, 11, 19 };
    int comb2[] = { 10, 20, 30 };

    final JFormattedTextField field1 = new JFormattedTextField(
        new CombinationFormatter());

    final JFormattedTextField field2 = new JFormattedTextField(
        new CombinationFormatter());

    JPanel pan = new JPanel();
    pan.add(new JLabel("Change the combination from"));
    pan.add(new JLabel("to"));

    JButton b = new JButton("Submit");
    b.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent ae) {
        try {
          field1.commitEdit(); // make sure current edit (if any) gets
                     // committed
        } catch (java.text.ParseException pe) {
        int oldc[] = (int[]) field1.getValue();
        int newc[] = (int[]) field2.getValue();
        // code to validate oldc[] and change to newc[] goes here

    JFrame f = new JFrame("CombinationFormatter Demo");
    f.setSize(360, 100);


Related examples in the same category

1.different configurations of JFormattedTextField: Numberdifferent configurations of JFormattedTextField: Number
2.Different configurations of JFormattedTextField: DateDifferent configurations of JFormattedTextField: Date
3.JFormattedTextField: an input mask (###) ###-#### for a telephone number
4.Using an InputVerifier with a formatted textfieldUsing an InputVerifier with a formatted textfield
5.A formatter for regular expressions to be used with JFormattedTextFieldA formatter for regular expressions to be used with JFormattedTextField
6.Field with different formats with focus and withoutField with different formats with focus and without
7.A quick demonstration of JFormattedTextFieldA quick demonstration of JFormattedTextField
8.Formatter Factory DemoFormatter Factory Demo
9.Formatted TextField DemoFormatted TextField Demo
10.Accepting Formatted InputAccepting Formatted Input
11.Formatted TextField ExampleFormatted TextField Example
12.Input Verification Demo Input Verification Demo
13.Creating a Text Field to Display and Edit a Phone Number
14.Creating a Text Field to Display and Edit a social security number
15.Make custom Input Text Formatter in Java
16.Support a date with the custom format: 2009-1-1
17.A BigDecimal object custom formatter
18.A decimal number with one digit following the decimal point;
19.Dynamically change the format
20.Creating a Text Field to Display and Edit a Number
21.Creating a Text Field to Display and Edit a Date
22.Format and validate input field in Java Swing
23.Input Verification Dialog Demo Input Verification Dialog Demo
24.A collection of formatted text fields and a button that displays the field values.