Unable to Dynamically Change panel
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.
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".
精彩评论