多个面板之间导航(Navigating between multiple panels)

2019-07-29 17:49发布

谁能告诉我如何去了解编码多间导航JPanel采取从事件触发类JButton从物体(板)自己? 我看了一下CardLayout 。 该面板可以从父面板发生的事件进行交换。 我想实现的是嵌入在面板点击按钮,应该就会消失或所需的面板应显示。 似乎无法找到一个解决方案。

Answer 1:

有一个关于CardLayout什么,防止开关卡从卡内孩子的行为。

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) { }
    }
}


Answer 2:

您可以使用JMenu,用JMenuItems ,而不是使用JButton的切换中间人卡



文章来源: Navigating between multiple panels