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. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 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. 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
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.