Question

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?

Was it helpful?

Solution

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);

            }
        });
    }
}

OTHER TIPS

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.

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