Communication Between JFrame Panels

by Joseph B. Cotton

I have two JFrames in my NetBeans application. On Frame A is a text box, and in Frame B is a button. I wish to push the button on B and have a message placed in the text box in A, (and visa versa).

To do this, I set a couple of static variables in my Main class to hold pointers to the FrameA and FrameB class instances. I opened FrameA in Main, and Opened FrameB in A. I set the static pointer to B in its constructor. Once the static pointers were set, I was able to call class methods from one to the other. Alternatively, I could set the JFrameA global pointer in the Frame A constructor, also.

Main has the two global variables

Frame A creates Frame B and also can execute a method in frame B (sets text in a text box)

In its constructor, Frame B sends its own identity up to the global variable. This allows Frame A to execute Frame B methods. Also here in FrameB, execute method in FrameA.

An alternative, that may be better for all but the simplest applications, is using the publish/subscribe design pattern, see The EventBus. With publish/subscribe, the button's action can call EventBus.publish("MessageForTextBox", textBox.getText()), and Frame B can call EventBus.subscribe("MessageForTextBox", subscriber) and the subscriber's onEvent method puts up the message box. Pub/sub avoids the coupling of the frames and the coordination between them (such as when they close). In Netbeans RCP, the Lookup API is a similar alternative.

Have a programming question or need help using Sun products or community technologies in your development projects? Get Sun Developer Expert Assistance! This online support service for developers provides technical assistance for code support, programming questions, and diagnostic advice to resolve problems. Buy Now

Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo