Question

I have a JFrame with cardlayout and two cards. I want the first card to be displayed for 5 seconds and then switched to the second.

I used the following code:

CardLayout cards=new CardLayout();
panel.setLayout(cards);
panel.add(first,"first");
panel.add(second,"second");
cards.show(panel,"first");
Thread.sleep(5000);
cards.show(panel,"second");

However the second card is directly shown.

Was it helpful?

Solution

Swing is single threaded. Youre blocking the EDT with the call to Thread.sleep preventing the first card from being painted. Swing Timers were designed to interact with Swing components. Use one instead to invoke CardLayout#show in the timer's ActionListener.

Timer timer = new Timer(5000, new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        cards.show(panel,"second");
    }
});
timer.setRepeats(false);
timer.start();

Read: Concurrency in Swing

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top