I have a program where I am trying to display one image and after 5 seconds it removes the image from the JLabel then displays the 2nd image but the 2nd image won't display by itself unless I click the the header or the bar on top of the window that the program creates. I want to have the image display automatically without me interacting with the window. Any help?
public void pictures(){
try{
BufferedImage myPicture = ImageIO.read(new File("round-1.jpg"));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
picLabel.setSize(800,600);
add(picLabel);
picLabel.setVisible(true);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run(){
picLabel.setVisible(false);
pictures2();
}
}, 5000);
}
catch(IOException e){
e.printStackTrace();
}
}
public void pictures2(){
try{
BufferedImage myPicture2 = ImageIO.read(new File("go.png"));
JLabel picLabel2 = new JLabel(new ImageIcon(myPicture2));
picLabel2.setSize(800,600);
add(picLabel2);
picLabel2.setVisible(true);
}
catch(IOException e){
e.printStackTrace();
}
}
Perhaps it is because the work (run method) for your timer task runs in a separate thread and is not in the Swing event-handling thread?
I suspect you should be calling SwingUtilities.invokeLater
in your timer's run method so that the changes to the label are done in the Swing event-handling thread.