What are the differences between a JTextField and a JFormattedTextField in Java?
JTextField
- JTextFeldis是最重要的组件之一,它允许用户以单行格式键入输入文本值。
- 当我们尝试在文本字段内输入一些输入时,JTextField可以生成一个ActionListener接口,并且每次插入符(即光标)改变位置时,它都可以生成一个CaretListener接口。
- JTextField也可以生成MouseListener和KeyListener接口。
例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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(); } } |
输出量
JFomattedTextField
- 格式化的文本字段是类JFormattedTextField的实例,该类是JTextField的直接子类。
- JFormattedTextField与普通的文本字段类似,不同之处在于JFormattedTextField用于控制用户键入的字符的有效性,并且可以与指定用户可以输入的字符的格式化程序关联。
- JFormattedTextField是Format类的子类,用于构建格式化的文本字段。我们可以创建一个格式化程序,必要时对其进行自定义。我们可以调用JFormattedTextField(Format format)构造函数,该构造函数接受Format类型的参数。
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 | 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(); } } |
输出量