Ali
Ali

Reputation: 7

Adding JPanel to JMenuItem

I have added buttons and text fields to a panel, but when I try to add the panel to the MenuItem nothing happens. I have defined an ActionListener for the MenuItem in which I am adding the JPanel. No error is detected by the compiler, but nothing happens when I click the MenuItem. How can I resolve this issue?

public class MenuFrame extends JFrame {
    private JMenu customers;
    private JMenu purchase;
    private JPanel panel1 = new JPanel();

    public MenuFrame() {
        JButton button = new JButton();
        panel1.add(button);
        customers = new JMenu("Customers");

        JMenuItem createInvoice = new JMenuItem("Create");
        JMenuItem updateInvoice = new JMenuItem("Update");
        JMenuItem deleteInvoice = new JMenuItem("Delete");

        sales.add(createInvoice);
        PanelHandler p = new PanelHandler(panel1);
        createInvoice.addActionListener(p);
    }

    private class PanelHandler implements ActionListener {
        private JPanel panel;

        public PanelHandler(JPanel p) {
            this.panel = p;
        }

        public void actionPerformed(ActionEvent e) {
            // getContentPane().removeAll();
            // getContentPane().setVisible(true);
            // JButton b=new JButton("Enter");
            // panel.add(b);
            panel.setVisible(true);
            add(panel, BorderLayout.SOUTH);
            getContentPane().doLayout();
            // update(getGraphics());
        }
    }
}

Upvotes: 0

Views: 1320

Answers (1)

camickr
camickr

Reputation: 324207

Don't invoke doLayout() directly.

When add (or remove) components from a visible GUI the basic code is:

panel.add(...);
panel.realidate();  // to invoke the layout manager
panel.repaint(); to repaint components

Upvotes: 1

Related Questions