Coder ACJHP Coder ACJHP - 2 months ago 10
Java Question

How to dynamically change JFrame background?

I have small problem with changing

JFrame
background image. First I've added background image with
JLabel
and application is working good. But now I need to change it dynamically.

I've tried this code :

label = new JLabel(new ImageIcon(Toolkit.getDefaultToo... // old background image

public void changeImage(){

label.setVisible(false);

label2 = new JLabel(new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("weatherall.gif"))));
setContentPane(label2); // new Background image
label2.setVisible(true);
repaint();

}
switch (cmb.getSelectedItem().toString()) {
case "ISTANBUL":
x = 0;
changeImage();
//some codes......vs.vs.
break;


Also I'v tried it with timer (
TimerTask
) every 1 sec. Refreshing frame

Anybody have an idea about this?

Answer

Now we need to create JLabel and set it size like background(stretch it) after that just add image into the JLabel and when u want to change it just change the image from same JLabel don't try adding another JLabel,it's not working!!...thats it.

JLabel label = new JLabel(new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource(localweather))));
setContentPane(label);//when u want to change background image just replace 'localweather' another image.
Comments