两个不同的 JFrame 之间的通信?

2022-01-24 00:00:00 java swing jframe

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

Hello as maybe you have heard about GIMP or something like that which uses different frames As a complete gui so I was wondering how to do such frames communications when both(maybe multiple) frames are loaded in memory and are visible.

我看过一些文章,但不是很满意,如果有人有好的例子或教程,请分享.

I have gone through some articles but they were not so satisfactory, if anyone have a good example or tutorial then please share.

问候阿洛克夏尔马

推荐答案

基本上就是在B帧中引用A帧,在A帧中引用B帧:

Basically, it's just a matter of having a reference to frame A in frame B, and a reference to frame B in frame A :

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

大多数时候,引入接口来解耦框架(侦听器等),或者使用中介来避免所有框架之间的过多链接,但您应该明白这一点.

Most of the time, interfaces are introduced to decouple the frames (listeners, etc.), or a mediator is used in order to avoid too much linkings between all the frames, but you should get the idea.

相关文章