I added my buttons
in a JPanel
(which has a border layout
, added the buttons to its south
position), then added another JPanel
cardsPanel
in the (center
position of the) parent panel, and gave it a CardLayout
. I want this cardsPanel
to be the container
for the cards (I mean the panels which will share the same screen space).
Now what I need to do is to to display those cards (I am calling the panels which will share the same screen space as cards) as a response to the buttons in the parent panel. But the buttons are located in the parent panel and their action listeners will obviously be located there too.
So the question is that how do I show
(by cardLayout.show()
) the panels located in a container class (with Cardlayout
) as a response to buttons located in another class (with BorderLayout
) ?
EDIT - QUESTION ABOUT ACTION:-
I hope to find implementing an Action
more useful than an ActionListener
. I also read that they can be reused, and used for the buttons which perform the same function. I have a few buttons which perform the function of flipping a particular card (i.e. displaying a particular panel in the CardLayout). I have written just one inner class and I want to use it for all the buttons.
So I will like to pass the button identifier (the string used to identify a button when we add the button to its parent e.g. String btnIdentifier= "1"; panel.add(button1, btnIdentifier);
) to the method actionPerformed() of this class, eventhough we are never explicitly calling actionPerformed(). So how can I pass the string identifier of the button to the actionPerformed() method so that I can use the same Action
for all my buttons.
Minimal Code:-
class Action extends AbstractAction{
Action(String text, ImageIcon icon){
super(text, icon);
}
public void actionPerformed(ActionEvent e) {
button1.setBorderPainted(true);
button1.setContentAreaFilled(true);
if (btnIdentifier=="1"){ //////ASSUMING THAT BUTTON IDENTIFIER HAS SOMEHOW BEEN PASSED TO THIS METHOD
FirstCard firstCard= new FirstCard();
cardsPanel.add(firstCard, btnIdentifier);
cardLayout.show(cardsPanel, btnIdentifier);
} else if (btnIdentifier=="2"){ //////ASSUMING THAT BUTTON IDENTIFIER HAS SOMEHOW BEEN PASSED TO THIS METHOD
SecondCard secondCard= new SecondCard();
cardsPanel.add(secondCard, btnIdentifier);
cardLayout.show(cardsPanel, btnIdentifier);
} else if (btnIdentifier=="3"){ //////ASSUMING THAT BUTTON IDENTIFIER HAS SOMEHOW BEEN PASSED TO THIS METHOD
ThirdCard thirdCard= new ThirdCard();
cardsPanel.add(thirdCard, btnIdentifier);
cardLayout.show(cardsPanel, btnIdentifier);
}
}
}
}