I have this program in which I'm using CardLayout. I have different panels with different attributes. I have a button called "Enter" that I decided to reuse on every panel, however each panel performs a different operation when the button is clicked. Is there a way to say, when button is clicked but I am at a specific panel, then do this. How can I point directly to a panel?
Asked
Active
Viewed 44 times
0
-
Where is the program? Have u forgotten to share the code? – Juned Ahsan Aug 11 '13 at 01:30
-
1For [example](http://stackoverflow.com/a/6432291/230513). – trashgod Aug 11 '13 at 01:45
-
I do have a code but I didn't think it was necessary to post it. I was just trying to ask a more general question about how to do a certain thing rather than something specific on my code. – polaris Aug 14 '13 at 01:34
2 Answers
3
First thing you must consider is: You can't add one button to many panels, every panel should have it's own component(s).
If you add one button to many panels say :
JButton b = new JButton("Button");
//....
pan1.add(b);
pan2.add(b);
pan3.add(b);
In such case, the button will be added to the last panel means pan3
, the other won't show the button.
Second, I would like to mention a @trashgod's
good example from comments, and also in case confusing, look at this example:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class CardLayoutDemo extends JFrame implements ActionListener {
private CardLayout cardLayout;
private JButton pan1,pan2;
private JPanel mainPanel;
public CardLayoutDemo(){
cardLayout = new CardLayout();
mainPanel = new JPanel(cardLayout);
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
pan1 = new JButton("To Second Panel");
pan2= new JButton ("To First Panel");
pan1.addActionListener(this);
pan2.addActionListener(this);
p1.setBackground(Color.green);
p2.setBackground(Color.BLUE.brighter());
p1.add(pan1);
p2.add(pan2);
mainPanel.add(p1,"1");
mainPanel.add(p2,"2");
cardLayout.show(mainPanel, "1");
add(mainPanel);
setDefaultCloseOperation(3);
setLocationRelativeTo(null);
setVisible(true);
pack();
}
@Override
public void actionPerformed(ActionEvent ev){
if(ev.getSource()==pan1)
cardLayout.show(mainPanel, "2");
else if(ev.getSource()==pan2)
cardLayout.show(mainPanel, "1");
}
public static void main(String...args){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new CardLayoutDemo().setVisible(true);
}
});
}
}

Azad
- 5,047
- 20
- 38
-
Thank you for the answer. I have used event handlers before but I wasn't sure if this was possible. I wanted to avoid having to many components in my code. However I decide to go ahead and create different buttons for each panel. – polaris Aug 14 '13 at 01:36
1
You can let the panel assign an ActionListener
to the button each time the card is created. That way the constructor for a specific panel can determine what the functionality of the button will be.

bas
- 1,678
- 12
- 23