将面板添加到面板

时间:2014-02-04 09:46:26

标签: java swing jframe jpanel

我正在构建一个Java程序。该程序的核心在JFrame中可视化,具有JMenuBar和各种JMenuItem和JMenu。关键是我向所有帧添加了一个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();
你能帮帮我吗?谢谢!

2 个答案:

答案 0 :(得分:3)

使用CardLayout而不是尝试添加和删除组件/面板。它更清洁,你不必担心可能出错的事情,比如你在这里面临的问题。

请参阅this example,了解它是多么简单和清洁。另请参阅How to Use CardLayout教程


附注

  • 组件只能有一个父容器。虽然我不认为这对你造成了问题。很高兴知道。首先,我看到您尝试将storicoPanel添加到您从未添加到JScrollPane的{​​{1}},JScrollPane。然后,您稍后将centerPanel添加到storicoPanel。此后centerPanel将不再是父母。

  • 我不确定您使用这个JScrollPane的是什么,但是您上课已经是carrelloFrame = new JFrame();,为什么要创建另一个?

  • 仅供参考,在动态添加组件时,您需要JFrame revalidate()。但是,在您的情况下,我完全反对添加和删除组件,因为这看起来像repaint()的完美案例。

答案 1 :(得分:0)

试试这些..

centralPanel.updateUI(); // or    
SwingUtilities.updateComponentTreeUI(getRootPane());

  1. SwingUtilities.invokeLater()

  2. 中执行您的框架代码
  3. 而不是repaint()来电updateUI()SwingUtilities.updateComponentTreeUI(getRootPane())更新 用户界面。