如何管理CardLayoutt中的许多JMenus?

时间:2015-12-27 18:08:17

标签: java swing

我有4种不同的观点,我希望它们有不同的JMenuloginPanel根本不存在)。我添加到卡片中的所有视图都会延伸JPanel并将其添加到卡片中。将JmenuBar设置为特定JPanel而不是JFrame是不可能的,而我希望每张卡都设置JMenuBar

public class MainFrame extends JFrame{

    public static JPanel cards;
    public Controller controller;

    public MainFrame() {

        cards = new JPanel(new CardLayout());

        controller = new Controller();

        setJMenuBar(controller.customMenuBar);  

        cards.add(controller.loginPanel, "login");
        cards.add(controller.prisonerAdd, "add");   
        cards.add(controller.prisonerPanel, "prisoner");
        cards.add(controller.searchView, "search");

        add(cards);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setExtendedState(JFrame.MAXIMIZED_BOTH);
        setVisible(true);
    }

这是Controller初始化JPanels并将actionListeners添加到JComponents:

public class Controller {

    public UserDatabase db = new UserDatabase();
    public LoginPanel loginPanel = new LoginPanel(); // extends JPanel
    public CustomMenuBar customMenuBar = new CustomMenuBar(); // extends JMenuBar
    public PrisonerAdd prisonerAdd = new PrisonerAdd(); // extends JPanel
    public PrisonerController prisonerController = new PrisonerController();
    public SearchView searchView = new SearchView(); //extends JPanel
    public PrisonerPanel prisonerPanel = new PrisonerPanel(); // extends JPanel

    public Controller() {

        loginPanel.addLoginListener(new LoginListener());
        customMenuBar.addLogoutListener(new LogoutListener());
        customMenuBar.addChangeViewListener(new ChangeViewListener());
        prisonerAdd.addPrisonerListener(new AddPrisonerListener());
        searchView.searchPanel.addSearchPrisonerListener(new SearchPrisonerListener());

    }

1 个答案:

答案 0 :(得分:3)

  1. 在每个面板中添加ComponentListener

  2. 处理componentShown(...)事件。

  3. 每当显示一个面板时,您都会更新相关面板的JMenuBar。