A JTextField can be used for plain text whereas a JFormattedTextField is a class that can extend JTextField and it can be used to set any format to the text that it contains phone numbers, e-mails, dates and etc.
JTextField
- A JTextFeld is one of the most important components that allow the user to type an input text value in a single line format.
- A JTextField can generate an ActionListener interface when we try to enter some input inside the text field and it can generate a CaretListener interface each time the caret (i.e. the cursor) changes position.
- A JTextField can also generate a MouseListener and KeyListener interfaces.
Example
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JTextFieldTest extends JFrame { JTextField jtf; public JTextFieldTest() { setTitle("JTextField Test"); setLayout(new FlowLayout()); jtf = new JTextField(15); add(jtf); jtf.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent ae) { System.out.println("Event generated: " + jtf.getText()); } }); setSize(375, 250); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String args[]) { new JTextFieldTest(); } }
Output
JFomattedTextField
- A formatted text field is an instance of the class JFormattedTextField which is a direct subclass of JTextField.
- A JFormattedTextField is like a normal text field except that is controls the validity of the characters the user type and it can be associated with a formatter that specifies the characters the user can enter.
- A JFormattedTextField is a subclass of Format class to build a formatted text field. We can create a formatter, customize it if necessary. We can call the JFormattedTextField(Format format) constructor which takes an argument of type Format.
import java.awt.*; import javax.swing.*; import javax.swing.text.*; public class JFormattedTextFieldTest extends JFrame { JFormattedTextField jftf; MaskFormatter mf; public JFormattedTextFieldTest() { setTitle("JFormattedTextField Test"); setLayout(new FlowLayout()); // A phone number formatter - (country code)-(area code)-(number) try { mf = new MaskFormatter("##-###-#######"); mf.setPlaceholderCharacter('#'); jftf = new JFormattedTextField(mf); jftf.setColumns(12); } catch(Exception e) { e.printStackTrace(); } add(jftf); setSize(375, 250); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } public static void main(String args[]) { new JFormattedTextFieldTest(); } }