外部 JPanle 不显示在 JFrame 上

External JPanle doesn't display on JFrame

我正在做一个大学项目。 该项目是一个单例 swing 应用程序。我维护了一个大型机,每次当用户单击不同的菜单选项卡时,我都会尝试使用新的外部面板更新大型机。问题是当我在大型机中加载外部 JPanel 时不显示任何内容。我还问我采取的方式是否正确。谢谢!

Mainframe.js

public class MainFrame extends JFrame {
JMenuBar menuBar;
JMenu homeshop, topCat, orders, login, register, exit;
ShopPanel shopPanel;
private OrderTrack orderTrack = new OrderTrack();

private void changePanel(JPanel panel) {
    getContentPane().removeAll();
    getContentPane().add(panel, BorderLayout.CENTER);
    getContentPane().doLayout();
    update(getGraphics());
}

private class MenuAction implements ActionListener {
    private JPanel panel;
    private MenuAction(JPanel pnl) {
        this.panel = pnl;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        changePanel(panel);
    }
}
private void initMenu() {
    // Menu setup
    menuBar = new JMenuBar();
    //Items
    homeshop = new JMenu("Shop");
    menuBar.add(homeshop);

    topCat = new JMenu("Top Books");
    menuBar.add(topCat);

    orders = new JMenu("Orders");
    //orders.addActionListener(new MenuAction(orderTrack));
    menuBar.add(orders);

    login = new JMenu("Login");
    menuBar.add(login);

    register = new JMenu("Register");
    menuBar.add(register);

    setJMenuBar(menuBar);
}
public void initMainFrame () {
    // Frame setup
    setSize(400, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    shopPanel = new ShopPanel();
    add(shopPanel);
    setVisible(true);
}
public MainFrame() {
    super("Welcome!");
    initMenu();
    initMainFrame();
}

}

ShopPanel.j

public class ShopPanel extends JPanel {
JPanel panel = new JPanel();
private JList<String> shopList;
private ArrayList<String> titleBooks;

public ShopPanel() {

    // QUERY //
    DBQuery bookTitle = new DBQuery();
    titleBooks = bookTitle.QueryOne("select title from book", "title");

    // GRIDBAG LAYOUT //
    panel.setLayout(new GridBagLayout());

    // label //
    JLabel lblInsertOrderId = new JLabel("Insert order ID");
    panel.add(lblInsertOrderId);

    // LIST OF BOOKS //
    shopList = new JList(titleBooks.toArray());
    shopList.setVisibleRowCount(6);
    shopList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    panel.add(shopList);
}

}

App.js

public class App {

public static void main (String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new MainFrame();
        }
    }); 
}

}

没有错误信息。

您的 ShopPanel 本身就是一个 JPanel。无需拥有成员 JPanel 并将所有内容添加到该成员。这不会显示,因为它不会添加到整个组件树中。尝试删除 "panel" 并在没有它的情况下执行所有操作,例如:add() 而不是 panel.add()。虽然没试过...