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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With