Swing (Problem in repainting)
Hi i have 2 Jpanels in a Jframe & in in ecah Jpanel 2 child Jpanels.in one of the child Jpanel i have a button/Label on click of which i need to repaint the Parent JFrame ( removing the existng panels & adding new panel )...I even tried passing the JFrame object but, it was behaving unpredictably....Can anybody help me in this regard.( u can even mail me at vizitesha@yahoo.com
To change components in containers you need to remove the old ones and replace them with new ones, then you need to validate the container before you repaint it.
final JLabel label1 = new JLabel("Label 1");
final JLabel label2 = new JLabel("Label2");
final JPanel lp = new JPanel( new BorderLayout() );
lp.add(label1, BorderLayout.NORTH );
JButton changer = new JButton("Click to change");
changer.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(label1.isShowing()) {
lp.remove(label1);
lp.add(label2, BorderLayout.NORTH);
} else {
lp.remove(label2);
lp.add(label1, BorderLayout.NORTH);
}
lp.validate();
lp.repaint();
}
} );
lp.add(changer, BorderLayout.SOUTH);
Something like this should do what you require. Work more on it the necessary effect.
ICE
Your description of the problem suggests that you may actually
want to use CardLayout rather than adding/removing. Alternately,
post a short, compileable, executable example and we can go
over specifics. As far as adding/removing goes, icewaker has
shown you the basic idea pretty clearly.