[英]Communication between two different JFrames?
您好,也許您聽說過GIMP或類似的使用不同幀的內容作為完整的gui,所以我想知道當兩個(也許多個)幀都加載到內存中並且可見時如何進行此類幀通信。
我瀏覽了一些文章,但並不令人滿意,如果有人有一個很好的例子或教程,請分享。
關於Alok Sharma
基本上,只需要在幀B中引用幀A,在幀A中引用幀B即可:
public class FrameA extends JFrame {
private FrameB frameB;
public void setFrameB(FrameB frameB) {
this.frameB = frameB;
}
public void foo() {
// change things in this frame
frameB.doSomethingBecauseFrameAHasChanged();
}
}
public class FrameB extends JFrame {
private FrameA frameA;
public void setFrameA(FrameA frameA) {
this.frameA = frameA;
}
public void bar() {
// change things in this frame
frameA.doSomethingBecauseFrameBHasChanged();
}
}
public class Main {
public static void main(String[] args) {
FrameA frameA = new FrameA();
FrameB frameB = new FrameB();
frameA.setFrameB(frameB);
frameB.setFrameA(frameA);
// make both frames visible
}
}
大多數時候,引入接口來解耦框架(偵聽器等),或者使用調解器來避免所有框架之間的過多鏈接,但是您應該明白這一點。
如果要在MVC類型模式中將“控件”邏輯與“視圖”邏輯分開,則這應該就像引用其他組件一樣簡單。
就像JFrame可能具有多個面板一樣,您的應用程序可以基於單個面板中的操作對多個面板進行更改。 您的應用程序可以具有多個框架,這些框架可能會受到單個框架中操作的影響。
考慮在基於Windows的NetBeans平台(Swing平台的RCP)上構建應用程序。 如果您喜歡多個窗口,則可以分離TopComponets。
您可以通過Lookup實例在TopComponents和Modules之間進行通信。
我已經晚了7年,但也許這對您來說仍然很有趣;)我通過實現Observer-Pattern解決了這個問題。
在我的示例中,有一個概述視圖( =observer
;來自DB的表)和一個詳細視圖( =observable
;其中包含來自概述視圖的一行)。 現在,我想編輯詳細視圖中的(在概述視圖中)選定的行,單擊保存按鈕,關閉詳細視圖並將更改notify
給(所有)觀察者。
public interface Observer {
public void notifyUpdate(Contact contact);
}
public interface Observable {
public void addObserver(Observer observer);
}
public class Detail extends JFrame implements Observable {
/* multiple observers possible */
private ArrayList<Observer> observers;
/* contact will be modified in detail-view and reported to overview-view */
private Contact contact;
public Detail() {
this.observers = new ArrayList<>();
}
@Override
public void addObserver(Observer observer) {
this.observers.add(observer);
}
/* trigger this methode e.g. by save-button, after modifiing contact */
protected void notifyObservers() {
/* multiple observers possible */
Iterator<Observer> observerIterator = this.observers.iterator();
while(observerIterator.hasNext()) {
/* report observer: constact has modified */
observerIterator.next().notifyUpdate(contact);
}
}
}
public class Contacts extends JFrame implements Observer {
private Detail detail;
public Contacts() {
detail = new Detail();
detail.setVisible(true);
detail.addObserver(this);
}
@Override
public void notifyUpdate(Contact contact) {
/* notifyUpdate was called from Observable */
/* process contact, DB update, update JTable */
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.