3

I have to views:

  1. MainWindowView (extends JFrame)
  2. ScanOptimisationView (extends JPanel)

So, I have the combobox in MainWindowView class. And I create ActionListener and bind it to this combobox. actionPerfomed() method of this ActionListener tries to add ScanOptimisationView panel to main window frame. Here is the code:

package ru.belaventcev.view;

import java.awt.Container;

public class MainWindowView extends JFrame{
    private int frmHeight = 525;
    private int frmWidth  = 650;

    public Container frmContainer;

    public static JButton btnCalc;

    public static JComboBox cbMethods;

    public MainWindowView(){
        setPreferredSize(new Dimension(frmWidth, frmHeight));
        setSize(frmWidth, frmHeight);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        frmContainer = getContentPane();
        frmContainer.setLayout(new MigLayout("", "[grow,center]", "[::30px,grow,center][grow,center][::500px,grow,center][::25px,grow,center]"));
        cbMethods = new JComboBox();
        cbMethods.setModel(new DefaultComboBoxModel(new JPanel[] {new ScanOptimisationView()}));
        cbMethods.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JPanel temp = (JPanel) cbMethods.getSelectedItem();
                frmContainer.add(temp, "cell 0 1,span");
            }
        });

        /*
         * If I uncomment this, panel is shown!
        JPanel temp = (JPanel) cbMethods.getSelectedItem();
        frmContainer.add(temp, "cell 0 1");
        */

        frmContainer.add(cbMethods, "cell 0 0,growx");



        btnCalc = new JButton("Расчитать");
        frmContainer.add(btnCalc, "cell 0 3,alignx right");

    }
}

Could you help me to understand - why panel doesn't shown with code in actionPerformed(), but it is shown, when I use the code below?

Dmitry Belaventsev
  • 6,347
  • 12
  • 52
  • 75

1 Answers1

5

In the non-working case, after your actionListener calls frmContainer.add(), you need to call frmContainer.validate(). From the Javadocs for Container.add():

"If a component has been added to a container that has been displayed, validate must be called on that container to display the new component."

When you are responding to the click, your container has, obviously, already been displayed. When you add the JPanel in the constructor your JFrame has not been displayed yet.

user949300
  • 15,364
  • 7
  • 35
  • 66