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

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Collections Data Structure
8. Database SQL JDBC
9. Design Pattern
10. Development Class
11. Email
12. Event
13. File Input Output
14. Game
15. Hibernate
16. J2EE
17. J2ME
18. JDK 6
19. JSP
20. JSTL
21. Language Basics
22. Network Protocol
23. PDF RTF
24. Regular Expressions
25. Security
26. Servlets
27. Spring
28. Swing Components
29. Swing JFC
30. SWT JFace Eclipse
31. Threads
32. Tiny Application
33. Velocity
34. Web Services SOA
35. XML
Microsoft Office Word 2007 Tutorial
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Java » Swing JFC » Formatted TextFieldScreenshots 
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 
*/
// CombinationFormatter.java
//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() {
    setOverwriteMode(false);
  }

  public Object stringToValue(String stringthrows 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 valuethrows 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)
        sb.append('-');
      sb.append(a[j]);
    }
    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)
      this.delta = delta;
    }

    public void actionPerformed(java.awt.event.ActionEvent ae) {
      JFormattedTextField ftf = getFormattedTextField()// from
                                 // AbstractFormtter
      if (ftf == null)
        return;
      String text = ftf.getText();
      if (text == null)
        return;
      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[hyphenCount0)
          a[hyphenCount0;
        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'
        ftf.setCaretPosition(pos);
      catch (Exception e) {
        return;
      }
    }
  }

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

  public static void main(String argv[]) {
    // a demo main() to show how CombinationFormatter could be used
    int comb1[] 351119 };
    int comb2[] 102030 };

    final JFormattedTextField field1 = new JFormattedTextField(
        new CombinationFormatter());
    field1.setValue(comb1);

    final JFormattedTextField field2 = new JFormattedTextField(
        new CombinationFormatter());
    field2.setValue(comb2);

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

    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
          field2.commitEdit();
        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
        //
      }
    });
    pan.add(b);

    JFrame f = new JFrame("CombinationFormatter Demo");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setContentPane(pan);
    f.setSize(360100);
    f.setVisible(true);
  }
}

           
       
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. Using an InputVerifier with a formatted textfieldUsing an InputVerifier with a formatted textfield
4. A formatter for regular expressions to be used with JFormattedTextFieldA formatter for regular expressions to be used with JFormattedTextField
5. Field with different formats with focus and withoutField with different formats with focus and without
6. A quick demonstration of JFormattedTextFieldA quick demonstration of JFormattedTextField
7. Formatter Factory DemoFormatter Factory Demo
8. Formatted TextField DemoFormatted TextField Demo
9. Accepting Formatted InputAccepting Formatted Input
10. Formatted TextField ExampleFormatted TextField Example
11. Input Verification Demo Input Verification Demo
12. Input Verification Dialog Demo Input Verification Dialog Demo
ww___w_._j___a___v_a___2_s_.___c_om_ | Contact Us
Copyright 2003 - 08 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.