java onchange,是否有“ onChange”消息?对于Java?

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.)

Any help would be much appreciated.

解决方案

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("");

}

}

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值