Bitcoin

Bitcoin
Bitcoin

JFormattedTextField Java

The JFormattedTextField allows us to create a text field that can accept a formatted input. In this example we create two formatted text fields that accept a valid phone number and date.
import javax.swing.*;
import javax.swing.text.MaskFormatter;
import javax.swing.text.DateFormatter;
import java.awt.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;

public class FormattedTextFieldExample extends JFrame {
    public FormattedTextFieldExample() {
        initComponents();
    }

    private void initComponents() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(new Dimension(200, 200));
        getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));

        MaskFormatter mask = null;
        try {
            //
            // Create a MaskFormatter for accepting phone number, the # symbol accept
            // only a number. We can also set the empty value with a place holder
            // character.
            //
            mask = new MaskFormatter("(###) ###-####");
            mask.setPlaceholderCharacter('_');
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //
        // Create a formatted text field that accept a valid phone number.
        //
        JFormattedTextField phoneField = new JFormattedTextField(mask);
        phoneField.setPreferredSize(new Dimension(100, 20));

        //
        // Here we create a formatted text field that accept a date value. We
        // create an instance of SimpleDateFormat and use it to create a
        // DateFormatter instance which will be passed to the JFormattedTextField.
        //
        DateFormat format = new SimpleDateFormat("dd-MMMM-yyyy");
        DateFormatter df = new DateFormatter(format);
        JFormattedTextField dateField = new JFormattedTextField(df);
        dateField.setPreferredSize(new Dimension(100, 20));
        dateField.setValue(new Date());

        getContentPane().add(phoneField);
        getContentPane().add(dateField);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new FormattedTextFieldExample().setVisible(true);
            }
        });
    }
}

Here are some other characters that can be used in the MaskFormatter class.
CharDescription
#For number
?For letter
AFor number or letter
*For anything
LFor letter, it will be converted to the equivalent lower case
UFor letter, it will be converted to the equivalent upper case
HFor hexadecimal value
To escape another mask character
ANOTHER EXAMPLE OF JFORMATTEDTEXTFIELD

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
import java.util.*;
  
public class Main extends JFrame
{
   public Main() throws Exception
   {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
   
  
      final JFormattedDateTextField formattedTf =
                   new JFormattedDateTextField();
      formattedTf.setValue(new Date());
  
      final JTextField normalTf = new JTextField(25);
      JButton button = new JButton("Get value");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            normalTf.setText(""+formattedTf.getValue());
         }
      });
  
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
      getContentPane().add(formattedTf);
      getContentPane().add(button);
      getContentPane().add(normalTf);
  
      formattedTf.setPreferredSize(normalTf.getPreferredSize());
   }
   
   public static void main(String args[]) throws Exception
   {
      Main main = new Main();
      main.setSize(300150);
      main.setVisible(true);
   }
}
  
class JFormattedDateTextField extends JFormattedTextField {
   Format format = new SimpleDateFormat("MM/dd/yyyy");
  
   public JFormattedDateTextField() {
      super();
      MaskFormatter maskFormatter = null;
      try {
         maskFormatter = new MaskFormatter("##/##/####");
      catch (ParseException e) {
         e.printStackTrace();
      }
  
      maskFormatter.setPlaceholderCharacter('_');
      setFormatterFactory(new DefaultFormatterFactory(maskFormatter));
      this.addFocusListener(new FocusAdapter() {
         public void focusGained(FocusEvent e) {
            if (getFocusLostBehavior() == JFormattedTextField.PERSIST)
               setFocusLostBehavior(JFormattedTextField.COMMIT_OR_REVERT);
            }
   
            public void focusLost(FocusEvent e) {
               try {
                  Date date = (Date) format.parseObject(getText());
                  setValue(format.format(date));
               catch (ParseException pe) {
                  setFocusLostBehavior(JFormattedTextField.PERSIST);
                  setText("");
                  setValue(null);
               }
            }
      });
   }
  
   public void setValue(Date date) {
      super.setValue(toString(date));
   }
  
   private Date toDate(String sDate) {
      Date date = null;
      if (sDate == nullreturn null;
      try {
         date = (Date) format.parseObject(sDate);
      }
      catch (ParseException pe) {
         // ignore
      }
  
      return date;
   }
  
   private String toString(Date date) {
      try {
         return format.format(date);
      catch (Exception e) {
         return "";
      }
   }
}

THE OUTPUT IS



No comments:

Post a Comment

Facebook