How to use CardLayout, with Menu as action listener?

徘徊边缘 提交于 2019-12-13 02:16:14

问题


I want to change the JPanel of a JFrame, using the CardLayout class. I have already run this example and it works.

Now I want to use as action listener, the JMenuItem; so If I press that JMenuItem, I want to change it, with a specific panel. So this is the 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);
        }
    }
}

Those are the Menu, the Controller and the Main:

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

The problem is that the JPanel doesn't change. What do you think is the problem ? I've already debugged it, and in the update() method, the correct String value arrives.


回答1:


You never add the cardPanel JPanel, the one using the CardLayout and displaying the "cards" to anything. You need to add it to your JFrame's contentPane for it to display anything. i.e.,

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


来源:https://stackoverflow.com/questions/30078997/how-to-use-cardlayout-with-menu-as-action-listener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!