Communication between two different JFrames?

后端 未结 4 2111
[愿得一人]
[愿得一人] 2020-12-06 07:54

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 bo

4条回答
  •  难免孤独
    2020-12-06 08:26

    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.

提交回复
热议问题