以下代码实现:
窗口内有一个文本框和两个按钮。
初始按钮为无效状态,在文本框内输入内容后,按钮变为有效状态!
但再将内容删除按钮不变为无效状态!
如果将被注释的哪行代码中的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);
}
}
}
窗口内有一个文本框和两个按钮。
初始按钮为无效状态,在文本框内输入内容后,按钮变为有效状态!
但再将内容删除按钮不变为无效状态!
如果将被注释的哪行代码中的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);
}
}
}
由此就可以看出,getText == null 永远都不成立。
而对3楼的回答,将txf.getText()==null改为txf.getText()=="",不对,我试过!
应该使用的是 getText().length()==0 对是否是空串进行判断;
如果你需要忽略空格的话,应该 getText().trim().length() == 0 对首尾空格进行剪裁
看来我还要更勤奋点学习java!!