[英]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.