import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Gui2 extends JFrame implements ActionListener {
JTextField jt;
JTextArea jta;
JTextArea jta2;
JButton jb1;
JButton jb2;
public static void main(String[] args) {
new Gui2().qq();
}
public void qq(){
JFrame jf = new JFrame("控件的相互控制");
jf.setSize(500,300);
jf.setLocation(200,200);
jf.setVisible(true);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
JLabel j1 = new JLabel("主题:Write Once,Run Anywhere. 昵称");
jt = new JTextField(15);
jta = new JTextArea();
jta2 = new JTextArea(2,30);
jb1 = new JButton("Clear");
jb2 = new JButton("Send");
jb1.addActionListener(this);
jb2.addActionListener(this);
JPanel jp1 = new JPanel();
JPanel jp2 = new JPanel();
jp1.setLayout(new FlowLayout());
jp1.add(j1);
jp1.add(jt);
FlowLayout f = new FlowLayout();
f.setAlignment(FlowLayout.LEFT);
jp2.setLayout(f);
jp2.add(jta2);
jp2.add(jb1);
jp2.add(jb2);
jf.add(jp1,new BorderLayout().NORTH);
jf.add(jta,new BorderLayout().CENTER);
jf.add(jp2,new BorderLayout().SOUTH);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == jb2){
b = jt.getText();
System.out.println(b);
if(jt.getText()!=null){//想问的是:这里的jt.getText()返回的是null吗?
//if语句中的判断是想实现如果没输入昵称就退出,可是在机器上跑起来不对。然后换成equals,也不对.......求指点。
jta.setText(jt.getText()+">"+jta2.getText());
jta2.setText(" ");
}
else{
System.out.println("Please enter your name");
System.exit(1);
}
}
if(e.getSource() == jb1){
jta.setText(" ");
jt.setText(" ");
jta2.setText(" ");
}
}
}
------解决思路----------------------
swing实现getText会调到这里,即便不输入也会产生一个String对象,不会为null。
public String getString(int where, int len) throws BadLocationException {
if (where + len > count) {
throw new BadLocationException("Invalid range", count);
}
return new String(data, where, len);
}
另:
jf.setSize(500,300);
jf.setLocation(200,200);
jf.setVisible(true);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
以上几行要放到函数尾部。
静态变量应使用类名引用,不需对象引用。如jf.EXIT_ON_CLOSE,new BorderLayout().NORTH 等。