在窗口A中有一个按钮,按下之后会弹出B窗口,B窗口中会输入账户与密码,有一个确定按钮,按下确定后会执行一系列的具体操作,但是同时需要把输入的账户传到A窗口中。
部分代码如下:
public void actionPerformed(ActionEvent e){
String cmd=e.getActionCommand();
 if(cmd.equals("Login")){
LoginWindow lw=new LoginWindow();

}
我搜索到的方法有把窗口A作为参数传给窗口B的,但是A窗口是在其他的地方被new出来的,在这个地方是在是不好作为参数传给窗口B啊。
至于在B中加入get 方法的方式。个人的理解是:在按下窗口A中的按钮Login时,代码块会全部被执行完,此时就算在new LoginWindow()语句后调用get方法,也会因为这个时候还没有输入而得不到用户的输入。
所以还有啥方法吗QAQ

解决方案 »

  1.   

    如果仅仅是传递字符串的话,直接给另一个类里的字段赋值即可,像这样:import java.awt.*;
    import java.awt.event.*;
    import java.util.*;public class FrameCommunication {
    public static void main(String[] args) {
    new FrameA().setVisible(true);
    }
    }class FrameA extends Frame {
    private static final long serialVersionUID = 1L;
    private TextField text;
    private Button showB; public FrameA() {
    this.setTitle("A窗体");
    this.setLayout(new BorderLayout());
    this.setSize(600, 400);
    text = new TextField();
    text.setSize(600, 100);
    text.setEditable(true);
    text.setVisible(true);
    this.add(text, BorderLayout.CENTER);
    showB = new Button("发送到B窗体");
    showB.addActionListener(new ActionListener() { @Override
    public void actionPerformed(ActionEvent e) {
    FrameB b = FrameB.getFrame();
    b.setMessage(text.getText());
    b.update();
    b.setVisible(true);
    text.setText("");
    }
    });
    this.add(showB, BorderLayout.SOUTH);
    this.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    }
    });
    }
    }class FrameB extends Frame {
    private static final long serialVersionUID = 1L;
    private static final FrameB instance = new FrameB();
    private String message;
    private TextArea print; private FrameB() {
    this.setTitle("B窗体");
    this.setSize(300, 200);
    print = new TextArea("");
    print.setEditable(false);
    this.add(print);
    this.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent e) {
    try {
    FrameB.this.setVisible(false);
    } catch (Throwable e1) {
    e1.printStackTrace();
    }
    }
    });
    } public static FrameB getFrame() {
    return instance;
    } public String getMessage() {
    return message;
    } public void setMessage(String message) {
    this.message = message;
    } public void update() {
    Calendar datetime = Calendar.getInstance();
    String time = datetime.get(Calendar.YEAR) + "年" + datetime.get(Calendar.MONTH) + "月"
    + datetime.get(Calendar.DAY_OF_MONTH) + "日 " + datetime.get(Calendar.HOUR_OF_DAY) + ":"
    + datetime.get(Calendar.MINUTE) + ":" + datetime.get(Calendar.SECOND);
    print.setText(print.getText() + "\n时间:" + time + "\n消息:" + message + "\n\n");
    }
    }
      

  2.   

    给B窗口写一个setA方法,把A传递过去
    至于你说的B内 get 还是算了,肯定需要把A传递过来的