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