如何按下按钮清除 jtextfield

发布于 2024-12-27 03:51:55 字数 112 浏览 4 评论 0原文

我有一个 JButton,当我按下它时,它必须清除 JTextfield 中的所有内容。我该怎么做?也许存在清除 JTextfield 的方法,或者我是否必须将该字段设置为 null

I have a JButton and when I push it, it has to clear all the content in a JTextfield. How can I do this? Maybe there exists a method to clear a JTextfield or do I have to set the field to null?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

时光瘦了 2025-01-03 03:51:55

< code>JTextField#setText 方法应该使用空的 String 作为文本。

至于对 JButton 单击做出反应,请为其附加一个 ActionListener。 Swing 教程非常详细地说明了这一切。

  1. 按钮教程
  2. 文本组件教程
  3. ActionListener 教程

The JTextField#setText method should do it with an empty String as text.

As for reacting on the JButton click, attach an ActionListener to it. The Swing tutorials illustrate this all in great detail.

  1. Button tutorial
  2. Text component tutorial
  3. ActionListener tutorial
白衬杉格子梦 2025-01-03 03:51:55

尝试使用 setText(String) 方法,带有空字符串参数:

myTextField.setText("");

Try using the setText(String) method with an empty string argument:

myTextField.setText("");
佞臣 2025-01-03 03:51:55

您可以调用 JTextField 类的 setText("") 方法,并传入一个空字符串作为参数。这会将 JTextField 中的内容替换为“”

http://docs.oracle.com/javase/7/docs/api/javax/swing/text/JTextComponent.html#setText(java.lang.String )

You can call the setText("") method of the JTextField class passing in an empty string as the parameter. This will replace what is in the JTextField with ""

http://docs.oracle.com/javase/7/docs/api/javax/swing/text/JTextComponent.html#setText(java.lang.String)

夜深人未静 2025-01-03 03:51:55

您甚至可以扩展 JTextField 类并添加一个名为 clear() 的方法。该类看起来像这样:

public class MyCustomJTextField extends JTextField {

    private static final String EMPTY_STRING = "";

    public void clear() {
        setText(EMPTY_STRING);
    }
}

You could even extend the JTextField class and add a method called clear(). That class would look something like this:

public class MyCustomJTextField extends JTextField {

    private static final String EMPTY_STRING = "";

    public void clear() {
        setText(EMPTY_STRING);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文