将 JPanel 添加到 JMenuItem

Adding JPanel to JMenuItem

我已将按钮和文本字段 添加到面板,但是当我尝试将面板添加到MenuItem 时没有任何反应。我已经为 MenuItem 定义了一个 ActionListener,我要在其中添加 JPanel。编译器没有检测到错误,但是当我单击 MenuItem 时没有任何反应。我该如何解决这个问题?

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

不要直接调用 doLayout()。

从可见 GUI 添加(或删除)组件时,基本代码为:

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