我正在构建一个Java程序。该程序的核心在带有JMenuBar以及各种JMenuItem和JMenu的JFrame中可视化。关键是我在所有框架上都添加了一个CentralPanel,但是如果我在CentralPanel中添加了一些内容,则仅当我调整主框架的大小,缩小或放大它时,它才会显示!
这是代码:

这是构造函数:

    public UserFrame(Sistema system)
    {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    this.setSize(screenSize.width, screenSize.height);
    storicoPanel = new JPanel();
    carrelloPanel = new JPanel();
    carrelloFrame = new JFrame();
    pane = new JScrollPane(storicoArea);
    close = new JButton("Chiudi");
    this.sistema = system;
    menu = new JMenuBar();
    this.setJMenuBar(menu);

    centralPanel = new JPanel();
    add(centralPanel);


在这里,我添加了centralPanel,在这里,在ActionListener中,我尝试向其中添加一些内容,但是它不起作用:

public ActionListener createVisualizzaStorico(final ArrayList<Acquisto> array)
{
    class Visualize implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        storicoPanel.removeAll();
        for(Acquisto a : array)
        {
            Articolo temp = a.getArticolo();
            if(temp instanceof Vacanza)
                storicoPanel.add(new VacanzaPanel((Vacanza)temp));
            else if(temp instanceof BeneDiConsumo)
                storicoPanel.add(new BeneDiConsumoPanel((BeneDiConsumo)temp));
            else if(temp instanceof Cena)
                storicoPanel.add(new CenaPanel((Cena)temp));
            else
                storicoPanel.add(new PrestazioniOperaPanel((PrestazioneOpera)temp));

        }

        centralPanel.add(storicoPanel);
        centralPanel.repaint();


请你帮助我好吗?谢谢!

最佳答案

使用CardLayout而不是尝试添加和删除组件/面板。它更加干净,您不必担心可能出问题的地方,例如您在这里所面临的问题。

请参阅this example以了解它是多么容易和清洁。另请参见How to Use CardLayout教程



旁注


一个组件只能有一个父容器。尽管我认为这不会给您带来麻烦。很高兴知道。首先,我看到您尝试将storicoPanel添加到JScrollPane,而您从未将其添加到JScrollPane。然后,您稍后将centerPanel添加到storicoPanel。此后,centerPanel将不再是父级。
我不确定您正在使用此JScrollPane做什么,但是您已经是班上的carrelloFrame = new JFrame();,为什么还要创建另一个?
仅供参考,在动态添加组件时,您需要JFramerevalidate()。但是,在您的情况下,我完全反对添加和删除组件,因为对于repaint()来说,这似乎是一个完美的案例。

10-07 19:06
查看更多