我正在尝试解决一个问题,其中声明我应该从框架中的textfield
(在本例中为名称)获取值,并将 Hello 放在前面然后再在框架中打印出来。
这是我的代码:
import java.awt.*;
import java.awt.event.*;
class NameWindow{
public static void main(String str[]){
MyFrame mf=new MyFrame();
mf.setVisible(true);
}
}
class WindowSensor extends WindowAdapter{
public void windowClosing(WindowEvent we){
System.out.println("Window is closing");
System.exit(0);
}
}
class ButtonSensor implements ActionListener{
MyFrame mf;
public ButtonSensor(MyFrame f){
mf=f;
}
public void actionPerformed(ActionEvent ae){
String name=mf.tf.getText();
mf.setMessage("Hello"+name);
mf.repaint();
}
}
class MyFrame extends Frame{
private String msg;
public TextField tf;
public MyFrame(){
super("Java Name Window");
msg="Enter Your Name:";
Button b=new Button("Say Hello!");
TextField tf=new TextField(20);
ButtonSensor bs=new ButtonSensor(this);
WindowSensor ws=new WindowSensor();
add(tf);
add(b);
addWindowListener(ws);
b.addActionListener(bs);
setSize(600,400);
setLayout(new FlowLayout());
}
public void setMessage(String s){
msg=s;
}
public void paint(Graphics g){
g.drawString(msg,30,50);
}
}