【问题标题】:How to check that the variable in a different class has been updated?如何检查不同类中的变量是否已更新?
【发布时间】:2012-02-14 20:59:56
【问题描述】:

不知道以前是否有人问过这个问题,这有点难以解释。

我有两个班,A班和B班

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

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

顺便说一句,使用 Java Swing,

谢谢

T

【问题讨论】:

  • 为什么不能使用textbox的actionPerformed(ActionEvent ae)来监控,让ClassA知道值被改变了?
  • 当用户单击确定按钮更新变量时,我正在使用它,但它正在更新 B 类中的变量

标签: java swing oop class object


【解决方案1】:

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

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);
}

【讨论】:

  • 什么是 MyFrame? atm 我只使用 private final JPanel contentPanel = new JPanel();
  • MyFrame 是包含回调方法的对象。它可以是任何类型。只是对象必须对用户输入的文本做一些事情。它是您示例中 A 类的实例。
  • 你能告诉我A类应该是什么样子吗,我不确定我是否完全理解
  • 啊,这让我发疯了,我将一些字符串传递给对话框,以便它们在文本字段中有一些默认值,因此不能使用 new MyDialog(this);跨度>
  • 如果我将 MyFrame 替换为 A 类的名称,那么 super(frame);不工作
【解决方案2】:

一般Observer Pattern处理这种情况

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多