Java Swing Advanced Part I

Now a big problem in swing that is not immediately apparent is that a JFrame can contain two JPanels each with a different set of fields and buttons and labels and so on and each of these JPanels are in their own classes so it is difficult to figure out how to make one affect the other. The solution presents itself in this manner: You call the other class and pass an instance of the calling class into it as you do.

For example:

JPanel1 has a button and JPanel2 has a textarea you want to change with the button. Both are currently visible and their buttons and text areas all seem fixed, but the action listener attached to the button can do the work we need. Something like…

new JPanel2().setText(this)

would WORK!

We just have to write a method within JPanel2 that will change the text area. Something like…

static void setText(JPanel1 jp1){

jp1.textArea.setText = (“It’s working!”);

}

work do the trick. The idea is we passed a copy of JPanel1 into JPanel2’s method called setText and locally it’ll be named jp1. So we gain access to all its methods and its class fields ( what would be called a global variable in most other programming languages) and so we can set it from within the JPanel2 and it affects the whole instance up the chain back to the JPanel1 which called JPanel2. Crazy huh?