Navigating between multiple panels

2019-03-05 04:15发布

问题:

Can anyone tell me how to go about coding for navigation between multiple JPanel classes taking the event trigger from JButton from the objects (panels) themselves? I have read about CardLayout. The panel can be swapped from the events happening in the parent panel. What I want to achieve is on click of a button embedded in the panel, it should should disappear or a desired panel should be displayed. Can't seem to find a solution.

回答1:

There is nothing about CardLayout that prevents switching cards from actions of children within the cards.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Testing extends JFrame {

    private JPanel cardHolder;
    private CardLayout cards;
    private static final String cardA = "A";
    private static final String cardB = "B";

    private class Switcher implements ActionListener{
        String card;        
        Switcher(String card) { this.card = card; }
        @Override
        public void actionPerformed(ActionEvent e) {
            cards.show(cardHolder, card);
        }
    }

    private void run() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JPanel pa = new JPanel();
        JButton ba = new JButton("Switch to B");
        ba.addActionListener(new Switcher(cardB));
        pa.add(ba);
        pa.setBackground(Color.CYAN);

        JPanel pb = new JPanel();
        JButton bb = new JButton("Switch to A");
        bb.addActionListener(new Switcher(cardA));
        pb.add(bb);
        pb.setBackground(Color.MAGENTA);

        cardHolder = new JPanel();
        cards = new CardLayout();
        cardHolder.setLayout(cards);
        cardHolder.add(pa, cardA);
        cardHolder.add(pb, cardB);
        add(cardHolder);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    new testing().run();
                }
            });
        } catch (Exception ex) { }
    }
}


回答2:

You can use JMenu with JMenuItems instead of to use the JButton for switching betweens Cards