2

I have 2 panels. The first panel has a combo box. depending on the value of the item in the combobox selected, a panel below it must change. in the action listener of the combo box, when I try to change the panel, it does not change. Why is this?

cb1.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            String s = (String) cb1.getSelectedItem();
            if (s.equals("Invoice")) {
                panel3Customizera();
                g.gridy = 2;
                remove(panel3);
                add(panel3, g);
            } else {
                panel3Customizerb();
                g.gridy = 2;
                add(panel3, g);
            }

        }
    });

panel3customizer's add elements into panel3.panel 3 is added to a jframe. The link to the entire code can be found here

jzd
  • 23,473
  • 9
  • 54
  • 76
Kaushik Balasubramanain
  • 1,248
  • 6
  • 28
  • 42
  • 2
    Instead of providing a link to your source code, which we subsequently have to download, provide an [SSCCE](http://sscce.org/). – mre Aug 05 '11 at 13:43

2 Answers2

5

You need to call revalidate and repaint on the container that holds your panel3 object and that here uses GridBagLayout after adding or removing components. Note that revalidate is only for objects derived from JComponent such as JPanel.

Edit 1
If you are adding directly to the JFrame, then you are adding in fact to its contentPane which is usually a JPanel. So an example of doing what I suggested would look something like this:

  cb1.addActionListener(new ActionListener() {
     @Override
     public void actionPerformed(ActionEvent e) {
        JPanel contentPane = (JPanel) getContentPane();
        String s = (String) cb1.getSelectedItem();
        if (s.equals("Invoice")) {
           panel3Customizera();
           g.gridy = 2;
           remove(panel3);
           contentPane.add(panel3, g);
        } else {
           panel3Customizerb();
           g.gridy = 2;
           contentPane.add(panel3, g);
        }
        contentPane.revalidate();
        contentPane.repaint();
     }
  });

but having said this, I have to put a big plug into mre's suggestion about using a CardLayout instead to swap views.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
4

Sounds like the bottom JPanel ought to be using CardLayout. Here's a tutorial on How to Use CardLayout.

And @Hovercraft Full Of Eels is right in his recommendation to invoke revalidate() and repaint() on the container object, since this will cause it to layout its components again and remove any visual "artifacts".

Community
  • 1
  • 1
mre
  • 43,520
  • 33
  • 120
  • 170