两个不同JFrame之间的通信?

Alo*_*lok 5 java swing jframe

你好,也许你已经听说过GIMP或类似的东西使用不同的框架作为一个完整的gui所以我想知道当两个(可能是多个)帧加载到内存中并且可见时如何进行这种帧通信.

我已经阅读了一些文章,但它们并不是那么令人满意,如果有人有一个很好的例子或教程那么请分享.

关心Alok sharma

JB *_*zet 7

基本上,只需要在帧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
    }
}
Run Code Online (Sandbox Code Playgroud)

大多数情况下,引入接口来解耦帧(侦听器等),或者使用中介来避免所有帧之间的过多链接,但是你应该明白这一点.