初学Swing遇到了麻烦。我想设计一个程序,输入你的名字就打出“你好+名字”,否则就打出“你还没告诉我你的名字。”,但是现在一直是“你好”,怎么办?
这是我的代码:
package MySwing;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Myswing {
JTextArea text;
String str;
public static void main(String[] args) {
Myswing gui=new Myswing();
gui.go();
}
public void go() {
JFrame frame=new JFrame("zzsy");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(800, 300);
JPanel panel=new JPanel();
JButton button1=new JButton("确定");
JButton button2=new JButton("退出");
JLabel label=new JLabel("输入你的名字:");
label.setFont(new Font("宋体",Font.BOLD,16));//设置字体
JTextField field=new JTextField(30);
field.setText("");
str=field.getText();
text=new JTextArea();
text.setLineWrap(true);
JScrollPane scroll=new JScrollPane(text);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
button1.addActionListener(new b1());
panel.setLayout(null);
button1.setBounds(50, 300, 100, 50);
button2.setBounds(200, 300, 100, 50);
label.setBounds(0, 0, 200, 40);
field.setBounds(150, 0, 100, 40);
text.setBounds(40,50,300,200);
panel.add(button1);
panel.add(button2);
panel.add(label);
panel.add(field);
panel.add(text);
panel.add(scroll);
frame.add(panel);
frame.setSize(400, 400);
frame.setVisible(true);
}
class b1 implements ActionListener{
public void actionPerformed(ActionEvent e1) {
if(str=="")
text.append("你还没告诉我你的名字。\n");
else
text.append("你好"+str+"! \n");
}
}
}