本文介绍了是否有“ onChange”消息?对于Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java编程比较陌生,我编写了一些放置JLabel的代码,其文本设置为JTextField后的 在此处输入文本。 (类似于Microsoft登录页面的功能)我想知道当用户开始在文本字段中键入内容时,是否可以删除JLabel的文本。 (或者甚至存在这样的事件处理程序。)

I am relatively new with Java programming, and I wrote some code that places a JLabel, with the text set to "Enter text here" behind a JTextField. (Similar to the way the Microsoft Sign-in page functions) I would like to know if there is a way to delete the text of the JLabel when the user begins typing in the text field. (Or if such an event handler even exists.)

任何帮助将不胜感激。

推荐答案

没有通用的 onChange 函数。但是,您可以在类中定义以下方法:,它是。您将使用如下所示的内容:

There is no generic onChange function. However there is a method you can define in a class that implements KeyListener which is public void keyPress. You would use this something like the following:

public class MyClass implements KeyListener {

    private JTextField myField;
    private JLabel myLabel;

    public MyClass() {
        myLabel = new JLabel("Enter text here");
        myField = new JTextField();
        myField.addKeyListener(this);
    }

    @Override
    public void keyPress(KeyEvent e) {
        myLabel.setText("");
    }
}

当然,您可以添加更多的灵活性对此,但以上是总体思路。例如,您可以确保 KeyEvent 来自适当的来源,正确的做法是:

There is of course a lot more flexibility you can add to this, but the above is the general idea. For example, you could make sure that the KeyEvent is coming from the appropriate source, as rightly you should:

@Override
public void keyPress(KeyEvent e) {
    if(e.getSource() == myField) {
        myLabel.setText(""):
    }
}

...以及许多其他东西。看看。

... and lots of other stuff. Have a look at Oracle's Event Listener tutorials.

这篇关于是否有“ onChange”消息?对于Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 20:11