以下代码实现:
窗口内有一个文本框和两个按钮。
初始按钮为无效状态,在文本框内输入内容后,按钮变为有效状态!
但再将内容删除按钮不变为无效状态!
如果将被注释的哪行代码中的if条件改为后面的条件就可以了,为什么???
import java.awt.*;
import java.awt.event.*;
public class Text9_11 extends Frame{

static Text9_11 frm=new Text9_11();
static TextField txf=new TextField();
static Button btn1=new Button("变黄"); 
static Button btn2=new Button("变蓝");

public static void main (String[] args) {
frm.setSize(300,200);
frm.setLayout(null);
txf.setBounds(50,50,200,30);
btn1.setBounds(60,100,80,30);
btn2.setBounds(160,100,80,30);
frm.add(txf);
frm.add(btn1);
frm.add(btn2);
txf.addTextListener(new A());
btn1.addActionListener(new A());
btn2.addActionListener(new A());
btn1.setEnabled(false);
btn2.setEnabled(false);
frm.setVisible(true);
}
static class A implements TextListener,ActionListener {
public void textValueChanged(TextEvent e) {
if(txf.getText()==null) { //txf.getText().length()==0
btn1.setEnabled(false);
btn2.setEnabled(false);
}
else {
btn1.setEnabled(true);
btn2.setEnabled(true);
  }
}
public void actionPerformed(ActionEvent e) {
Button btn=(Button)e.getSource();
if(btn==btn1)
txf.setForeground(Color.yellow);
else if(btn==btn2)
txf.setForeground(Color.blue);
}
}

解决方案 »

  1.   

    getText()返回的是""可以是使用"".equals(txf.getText())
      

  2.   

    setText:将此 TextComponent 文本设置为指定文本。如果该文本为 null 或空,则具有只删除旧文本的效果。getText:返回 TextComponent 文本,默认为空串
    由此就可以看出,getText == null 永远都不成立。
      

  3.   

    当把输入框的内容消除后,txf.getText()得到的值为 "", 不是 null所以无法让按钮再变灰。
      

  4.   

    在下才疏学浅,对1楼2楼的回答,不甚理解,可否说的简单点!!
    而对3楼的回答,将txf.getText()==null改为txf.getText()=="",不对,我试过!
      

  5.   

    1、如果初始化JTextField,并没有在构造函数赋值,没有调用setText赋值,那么这时候调用getText获得的是一个空串;2、对JTextField赋值,那么会将之前的text替换,设置成新的text;如果使用setText(null)/setText(""),也仅仅是将原有的text使用空串置换,所以setText(null)也并不能使getText返回null;
    应该使用的是 getText().length()==0 对是否是空串进行判断;
    如果你需要忽略空格的话,应该 getText().trim().length() == 0 对首尾空格进行剪裁
      

  6.   

    空串不等于null????
    看来我还要更勤奋点学习java!!