I have a class A ( which is a JFrame with card layout ). Two other classes B and C ( both are JPanels ). Class A initially displays an instance of the class B in its content pane. When a button is hit in the class B, I want to change the contents of the content pane of class A and display an instance of class C in the contentPane of class A. Please tell me how can we do this (handling the action event generated by the button in class B). One possibility is to make B and C inner class of Class A, so that they can access the cardlayout object of the class A to change the object it displays. Any other way of doing this?


Just have B and C take a reference to A (the frame) in their constructors. The JPanel components already have a method to getParent(), but it's easier to just pass the reference so you don't have to worry about container nesting and finding the right parent. Your action listener on B can then handle what is shown in A easily.

Just another note: I would recommend B just calling a method on A to handle the state change. That way A can handle it's own internal behavior as needed and B won't be mucking around in the guts of another class.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.