Navigating between multiple panels

后端 未结 2 1781
不知归路
不知归路 2021-01-26 00:17

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

相关标签:
2条回答
  • 2021-01-26 01:11

    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) { }
        }
    }
    
    0 讨论(0)
  • 2021-01-26 01:14

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

    0 讨论(0)
提交回复
热议问题