(JPanel切换)在两个面板切换之间添加延迟(java)

时间:2016-05-11 11:40:59

标签: java jpanel switching

我试图在两个JPanels之间添加延迟,切换到同一个JFrame, 两者都在循环中改变可见性类型。 我也尝试thread.sleep但它不起作用 提前谢谢:)

面板1颜色为红色

面板2颜色为黑色

 for (int i = 0; i < LENGTH; i++) {
    panel1.setVisible(true)
/*************************************
   here i want to add delay 
**************************************/  
    panel1.setVisible(false)
    panel2.setVisible(true);
    for (int k = 0; k < rSIZE; k++) {
        tempr[i][k].setBackground(labelsGrid[i][k].getBackground());
    }
}

1 个答案:

答案 0 :(得分:1)

您需要使用Swing Timers来触发UI切换之间的延迟。这是一个简单的例子。

package app;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class App extends JFrame
{
    private JLabel label;
    private Timer timer;
    private int counter = 10; // the duration
    private int delay = 1000; // every 1 second
    private static final long serialVersionUID = 1L;

    public App()
    {
        super("App");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        label = new JLabel("Wait for " + counter + " sec", JLabel.CENTER);
        JPanel contentPane = (JPanel) getContentPane();
        contentPane.add(label, BorderLayout.CENTER);
        contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        pack();

        ActionListener action = new ActionListener()
        {   
            @Override
            public void actionPerformed(ActionEvent event)
            {
                if(counter == 0)
                {
                    timer.stop();
                    label.setText("The time is up!");
                }
                else
                {
                    label.setText("Wait for " + counter + " sec");
                    counter--;
                }
            }
        };

        timer = new Timer(delay, action);
        timer.setInitialDelay(0);
        timer.start();

        setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new App();
            }
        });
    }
}

这个简单的计时器将每秒触发ActionListener,并在递减计数器值后更新标签。