多个面板之间导航 [英] Navigating between multiple panels

查看:158
本文介绍了多个面板之间导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我如何去从的JButton 编码多之间的导航走的是事件触发的JP​​anel 班从物体(板)本身?我读过关于 CardLayout 。所述面板可从在父面板发生的事件被交换。我想实现的是嵌在面板点击按钮,应该就会消失或所需的面板应显示。似乎无法找到解决的办法。

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.

推荐答案

有任何关于CardLayout是prevents从卡内对儿童的行动交换卡。

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

这篇关于多个面板之间导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆