JFrame
has a defaultBorderLayout
. Add components without specifying aBorderLayout
position will automatically add it to theBorderLayout.CENTER
. Each position can only have one component. The last component you add will be the only one visible. See more at How to Use BorderLayoutAvoid using
Thread.sleep
. If you want animation, use ajavax.swing.Timer
. See more at How to use Swing Timers. Using this method, you can do something like thisJLabel iconLabel = new JLabel(image); ... Timer timer = new Timer(3000, new ActionListener(){ public void actionPerformed(ActionEvent e) { iconLabel.setIcon(image1); } }); timer.setRepeats(false); timer.start();
Instead of trying to add a new label, just change the icon.
Also don't set the size of your frame. Just pack it. The image will set the preferred size of the
JLabel
for you andpack
ing the frame will assure the icon is fully visible.
As an aside, when you add components after the container is visible, you need to revalidate()
and repaint()
the container.
Try running this example. Just put in your path to the image icons.
import java.awt.event.*;
import javax.swing.*;
public class ChangeIcon {
public ChangeIcon() {
final ImageIcon image = new ImageIcon("image.jpg");
final ImageIcon image1 = new ImageIcon("image1.jpg");
final JLabel iconLabel = new JLabel(image);
Timer timer = new Timer(3000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
iconLabel.setIcon(image1);
}
});
timer.setRepeats(false);
timer.start();
JFrame frame = new JFrame();
frame.add(iconLabel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ChangeIcon();
}
});
}
}