Question

I have a set of JPanels arranged in CardLayout. The issue is that when I change things in one JPanel, I want the changes to be reflected in another JPanel that is a card in the same deck. I have a refresh() method defined on each of these JPanel objects but I cannot call them using the syntax that is used for shifting cards. (Here p is the container card for the deck of cards)

CardLayout cardLayout=(CardLayout)(p.getMenuCard().getLayout());
cardLayout.show(p.getMenuCard(),"Card name");

I want to call the refresh() method but I don't know how to do that in CardLayout. Please help.

Was it helpful?

Solution

If we suppose that each of your "card" panels implement an interface that defines the refresh() method, then you could do:

interface Refreshable {
    void refresh();
}

class Card1 extends JPanel implements Refreshable {...}
...

// Changing the selected card panel
cardlayout.show(deckpanel, "card name");
for (component card: deckpanel.getComponents()) {
    ((Refreshable) card).refresh();
}

This is according to my understanding of your problem. Don't hesitate to edit your question to clarify further if this doesn't answer your problem.

OTHER TIPS

I have a set of JPanels arranged in CardLayout. The issue is that when I change things in one JPanel, I want the changes to be reflected in another JPanel that is a card in the same deck. I have a refresh() method defined on each of these JPanel objects but I cannot call them using the syntax that is used for shifting cards. (Here p is the container card for the deck of cards)

The one thing (CardLayout and swapping JPanels) has nothing to do with the other (one class changing state based on another class's state). What you need is for either the class making the initial changes to "push" this information to the other class that is supposed to respond to the changes, often by calling a setter method from the second class. The other option is to have the second class "pull" the information from the first class by using a listener, perhaps a PropertyChangeListener. But again, neither of these solutions -- or any solution whatsoever -- has anything to do with the CardLayout or swapping views.

For more specific advice for your current situation, consider creating a small compilable and runnable app that has no outside dependencies (images, database, etc), and that demonstrates your problem, an SSCCE, and post it here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top