Coder ACJHP Coder ACJHP - 1 year ago 97
Java Question

How to dynamically change JFrame background?

I have small problem with changing

background image. First I've added background image with
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(){


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

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

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

Anybody have an idea about this?

Answer Source

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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download