Navigating between multiple panels

孤者浪人 提交于 2019-12-02 19:08:07

问题


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



来源:https://stackoverflow.com/questions/10901352/navigating-between-multiple-panels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!