JTextField ใช้สำหรับข้อความธรรมดา ในขณะที่ JFormattedTextField ขยายจาก JTextField ใช้ตั้งค่ารูปแบบข้อความที่มีอยู่ เช่น เบอร์โทรศัพท์, อีเมล, วันที่ เป็นต้น
JTextField
- JTextField เป็นคอมโพเนนต์สำคัญที่สุด ให้ผู้ใช้พิมพ์ค่าข้อความในรูปแบบบรรทัดเดียว
- JTextField สร้าง ActionListener เมื่อพยายามป้อนข้อมูล และ CaretListener ทุกครั้งที่เคอร์เซอร์เปลี่ยนตำแหน่ง
- JTextField ยังสร้าง MouseListener และ KeyListener ได้อีกด้วย
ตัวอย่าง JTextField
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();
}
}
ผลลัพธ์

JFormattedTextField
- Formatted Text Field เป็นอินสแตนซ์ของ JFormattedTextField ซึ่งเป็นคลาสย่อยโดยตรงของ JTextField
- JFormattedTextField คล้าย Text Field ธรรมดา แต่ควบคุม ความถูกต้องของตัวอักษร ที่ผู้ใช้พิมพ์ และเชื่อมโยงกับ Formatter ที่ระบุตัวอักษรที่อนุญาต
- JFormattedTextField เป็นคลาสย่อยของ Format class สร้าง formatted text field สร้าง formatter ปรับแต่งได้ เรียกคอนสตรัคเตอร์ JFormattedTextField(Format format) ที่รับอาร์กิวเมนต์แบบ 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());
// ฟอร์แมตเตอร์เบอร์โทร - (รหัสประเทศ)-(รหัสพื้นที่)-(หมายเลข)
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();
}
}
ผลลัพธ์
