如何使用CardLayout,将Menu作为动作侦听器?

时间:2015-05-06 13:59:49

标签: java swing cardlayout

我想使用CardLayout类更改JFrame的JPanel。 我已经运行了this示例,但它确实有效。

现在我想用作动作监听器,JMenuItem;所以,如果我按下那个JMenuItem,我想用特定的面板来改变它。所以这是JFrame:

public class FantaFrame extends JFrame implements Observer {

    private static final long serialVersionUID = 1L;
    private JPanel cardPanel = new JPanel();
    private CardLayout cardLayout = new CardLayout();

    public FantaFrame(HashMap<String, JPanel> fantaPanels) {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("FantaCalcio App");
        setSize(500, 500);
        cardPanel.setLayout(cardLayout);
        setPanels(fantaPanels);

    }

    public void update(Observable o, Object arg) {
        cardLayout.show(cardPanel, arg.toString());
    }

    private void setPanels(HashMap<String, JPanel> fantaPanels) {
        for (String name : fantaPanels.keySet()) {
            cardPanel.add(fantaPanels.get(name), name);
        }
    }
}

这些是菜单,控制器和主菜单:

    private void pressed(){
        home.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                controller.changePanel(home.getText());
            }
        });
    }
   public class Controller extends Observable {


    public void changePanel(String panel){
        setChanged();
        notifyObservers(panel);
    }
}
    public static void main(String[] args) {
        fantaPanels.put("Login", new LoginPanel());
        Controller controller = new Controller();
        MenuBarApp menuApp = new MenuBarApp(controller);
        FantaFrame frame = new FantaFrame(fantaPanels);
        frame.setJMenuBar(menuApp);
        controller.addObserver(frame);
        frame.setVisible(true);
    }

问题在于JPanel没有改变。您认为这个问题是什么? 我已经调试过了,在update()方法中,正确的String值到了。

1 个答案:

答案 0 :(得分:2)

你永远不会添加cardPanel JPanel,使用CardLayout并向任何东西显示“牌”。您需要将其添加到JFrame的contentPane中,以便显示任何内容。即,

public FantaFrame(HashMap<String, JPanel> fantaPanels) {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setTitle("FantaCalcio App");
    setSize(500, 500);
    cardPanel.setLayout(cardLayout);
    add(cardPanel, BorderLayout.CENTER); // ****** add this line ******
    setPanels(fantaPanels);
}