温馨提示×

java怎么实现点击按钮清空文本框

小亿
100
2023-11-16 12:04:23
栏目: 编程语言

在Java中,可以通过使用按钮的事件监听器来实现点击按钮清空文本框的功能。下面是一个实现的示例代码:

import javax.swing.*;
import java.awt.event.*;

public class ClearTextFieldExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Clear Text Field Example");

        JTextField textField = new JTextField();
        textField.setBounds(50, 50, 200, 30);

        JButton button = new JButton("Clear");
        button.setBounds(100, 100, 100, 30);

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                textField.setText(""); // 清空文本框
            }
        });

        frame.add(textField);
        frame.add(button);

        frame.setSize(300, 200);
        frame.setLayout(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

在这个示例代码中,创建了一个JFrame窗口,其中包含一个文本框JTextField和一个按钮JButton。按钮使用addActionListener方法添加了一个事件监听器,当按钮被点击时,事件监听器中的actionPerformed方法会被调用,从而实现清空文本框的功能。在actionPerformed方法中,通过textField.setText("")将文本框的内容设置为空字符串,即实现了清空文本框的效果。

0