Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communication between two different JFrames?

Tags:

java

swing

jframe

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.

Regards Alok sharma

like image 218
Alok Avatar asked Feb 26 '11 13:02

Alok


2 Answers

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.

like image 105
JB Nizet Avatar answered Oct 05 '22 21:10

JB Nizet


If you are separating out your "Control" logic from your "View" logic in a MVC type pattern this should be as simple as just referencing a different component.

Just like a JFrame might have multiple panels and your application can make changes to several panels based on actions in a single panel. Your application can have multiple frames that can be affected by actions in a single frame.

like image 27
jzd Avatar answered Oct 05 '22 21:10

jzd