繁体   English   中英

如何检查其他类中的变量是否已更新?

[英]How to check that the variable in a different class has been updated?

不知道以前是否曾问过这个问题,很难解释。

我有2节课,A级和B级

类A创建类B的实例(这是使用JDialog的对话框)。 然后要求用户输入文本(存储在String变量中)。

我如何告诉A类用户现在已经更新了变量并获得了它的副本?

使用Java Swing,

谢谢

Ť

通常, 观察者模式处理此类情况

如果对话框是模式对话框,则代码将被阻塞,直到对话框关闭:

dialog.setVisible(true);
// blocked here until the dialog is closed. The dialog stores the input in a
// field when OK is clicked in the dialog
if (dialog.getTextInputtedByTheUser() != null) {
    ...

如果对话框不是模式对话框,则需要在验证发生时使其调用回调方法。 这就是MyFrame会包含的内容

private void showDialog(
    MyDialog dialog = new MyDialog(this);
    dialog.setVisible(true);
}

public void userHasInputSomeText(String text) {
    // do whatever you want with the text
    System.out.println("User has entered this text in the dialog: " + text);
}

并在MyDialog中:

private MyFrame frame;
public MyDialog(MyFrame frame) {
    super(frame);
    this.frame = frame;
}
...
private void okButtonClicked() {
    String text = textField.getText();
    frame.userHasInputSomeText(text);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM