JTextField(单行输入文本)详解
JTextField 是 Java Swing 中最常用的文本输入组件,用于接收用户单行文本输入。

基本使用
import javax.swing.*;
import java.awt.*;
public class JTextFieldDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("JTextField 示例");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLayout(new FlowLayout());
// 创建 JTextField
// 1. 无参构造
JTextField textField1 = new JTextField();
textField1.setColumns(20); // 设置列数(宽度)
// 2. 指定列数
JTextField textField2 = new JTextField(15);
// 3. 指定初始文本
JTextField textField3 = new JTextField("请输入内容...");
// 4. 指定初始文本和列数
JTextField textField4 = new JTextField("初始文本", 20);
frame.add(new JLabel("用户名:"));
frame.add(textField1);
frame.add(new JLabel("密码:"));
frame.add(textField2);
frame.setVisible(true);
}
}
常用方法
public class JTextFieldMethods {
public static void main(String[] args) {
JTextField textField = new JTextField(20);
// 获取和设置文本
String text = textField.getText(); // 获取文本
textField.setText("新文本"); // 设置文本
textField.setText(""); // 清空文本
// 编辑控制
textField.setEditable(true); // 设置可编辑
textField.setEditable(false); // 设置不可编辑(只读)
boolean editable = textField.isEditable(); // 检查是否可编辑
// 启用/禁用
textField.setEnabled(true); // 启用
textField.setEnabled(false); // 禁用(灰色不可用)
// 选择文本
textField.selectAll(); // 全选
textField.select(0, 3); // 选择部分文本(开始位置,结束位置)
textField.select(2, 5); // 选择第2到第5个字符
String selectedText = textField.getSelectedText(); // 获取选中的文本
// 光标操作
textField.setCaretPosition(0); // 设置光标位置
int position = textField.getCaretPosition(); // 获取光标位置
textField.setCaretColor(Color.RED); // 设置光标颜色
// 提示文本(Java 7+)
textField.setToolTipText("请输入用户名"); // 设置提示信息
}
}
事件监听
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class JTextFieldEvents extends JFrame {
private JTextField textField;
private JLabel label;
public JTextFieldEvents() {
setTitle("JTextField 事件示例");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
textField = new JTextField(20);
label = new JLabel("等待输入...");
// ActionListener - 按回车时触发
textField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
label.setText("输入内容: " + text);
}
});
// 也可以使用 Lambda(Java 8+)
textField.addActionListener(e -> {
label.setText("按回车: " + textField.getText());
});
// DocumentListener - 文本内容变化时触发
textField.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
@Override
public void insertUpdate(javax.swing.event.DocumentEvent e) {
label.setText("正在输入...");
}
@Override
public void removeUpdate(javax.swing.event.DocumentEvent e) {
label.setText("删除内容...");
}
@Override
public void changedUpdate(javax.swing.event.DocumentEvent e) {
// 对于 JTextField 通常不使用
}
});
// FocusListener - 焦点变化
textField.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
textField.setBackground(Color.WHITE);
textField.selectAll(); // 获取焦点时全选
}
@Override
public void focusLost(FocusEvent e) {
textField.setBackground(new Color(240, 240, 240));
}
});
add(new JLabel("输入内容:"));
add(textField);
add(label);
setVisible(true);
}
public static void main(String[] args) {
new JTextFieldEvents();
}
}
完整示例 - 登录界面
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoginExample extends JFrame {
private JTextField usernameField;
private JPasswordField passwordField;
private JButton loginButton;
private JLabel messageLabel;
public LoginExample() {
setTitle("登录系统");
setSize(350, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// 使用 GridBagLayout 进行布局
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
// 用户名
gbc.gridx = 0;
gbc.gridy = 0;
add(new JLabel("用户名:"), gbc);
usernameField = new JTextField(15);
usernameField.setToolTipText("请输入用户名");
gbc.gridx = 1;
gbc.gridy = 0;
add(usernameField, gbc);
// 密码
gbc.gridx = 0;
gbc.gridy = 1;
add(new JLabel("密码:"), gbc);
passwordField = new JPasswordField(15);
passwordField.setToolTipText("请输入密码");
gbc.gridx = 1;
gbc.gridy = 1;
add(passwordField, gbc);
// 登录按钮
loginButton = new JButton("登录");
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.CENTER;
add(loginButton, gbc);
// 消息标签
messageLabel = new JLabel("");
messageLabel.setForeground(Color.RED);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 2;
add(messageLabel, gbc);
// 事件处理
loginButton.addActionListener(e -> {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
if (username.isEmpty() || password.isEmpty()) {
messageLabel.setText("用户名和密码不能为空!");
} else if (username.equals("admin") && password.equals("123456")) {
messageLabel.setForeground(Color.GREEN);
messageLabel.setText("登录成功!");
} else {
messageLabel.setForeground(Color.RED);
messageLabel.setText("用户名或密码错误!");
}
});
// 按回车键触发登录
passwordField.addActionListener(e -> loginButton.doClick());
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new LoginExample());
}
}
验证和格式化
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class InputValidation {
public static void main(String[] args) {
JFrame frame = new JFrame("输入验证");
frame.setSize(300, 150);
frame.setLayout(new FlowLayout());
// 限制只能输入数字
JTextField numberField = new JTextField(10);
((AbstractDocument) numberField.getDocument()).setDocumentFilter(
new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset, String text,
AttributeSet attr) throws BadLocationException {
if (text.matches("\\d*")) { // 只允许数字
super.insertString(fb, offset, text, attr);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs) throws BadLocationException {
if (text.matches("\\d*")) {
super.replace(fb, offset, length, text, attrs);
}
}
}
);
// 限制输入长度
JTextField limitedField = new JTextField(10);
((AbstractDocument) limitedField.getDocument()).setDocumentFilter(
new DocumentFilter() {
private int maxLength = 5;
@Override
public void insertString(FilterBypass fb, int offset, String text,
AttributeSet attr) throws BadLocationException {
if (fb.getDocument().getLength() + text.length() <= maxLength) {
super.insertString(fb, offset, text, attr);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs) throws BadLocationException {
if (fb.getDocument().getLength() - length + text.length() <= maxLength) {
super.replace(fb, offset, length, text, attrs);
}
}
}
);
frame.add(new JLabel("数字:"));
frame.add(numberField);
frame.add(new JLabel("限制5字符:"));
frame.add(limitedField);
frame.setVisible(true);
}
}
常用属性设置
// 外观样式
textField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
textField.setForeground(Color.BLUE); // 文字颜色
textField.setBackground(Color.WHITE); // 背景颜色
textField.setHorizontalAlignment(JTextField.CENTER); // 对齐方式:LEFT, CENTER, RIGHT
// 边框
textField.setBorder(BorderFactory.createLineBorder(Color.GRAY));
textField.setBorder(BorderFactory.createEtchedBorder());
textField.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("输入框"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)
));
// 大小设置
textField.setPreferredSize(new Dimension(200, 30));
textField.setMinimumSize(new Dimension(100, 25));
textField.setMaximumSize(new Dimension(300, 35));
JTextField 是 Swing 中最基础但最常用的组件之一,掌握它可以构建各种文本输入交互界面。