如何检查不同类中的变量是否已更新?

use*_*059 5 java oop swing class object

不确定以前是否曾经问过,这有点难以解释.

我有2个班,A班和B班

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

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

使用Java Swing btw,

谢谢

Ť

JB *_*zet 2

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

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) {
    ...
Run Code Online (Sandbox Code Playgroud)

如果对话框不是模态的,那么您需要在验证发生时使其调用回调方法。这就是 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);
}
Run Code Online (Sandbox Code Playgroud)

在我的对话框中:

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