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.

有帮助吗?

解决方案

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top