Requirements
1. the user clicks the button(Go to animation page) at page one
2. the user will be directed to page two whereby an animation is played for 5 seconds
3. after 5 seconds, the user will be directed to page three.
I am trying to delay a page for around 5seconds before it loads another page.
I used thread.sleep(5000) in my Jbutton and check the current thread state. But this is wrong as
as soon as the current thread state is TIMED_WAITING, it will go straight to third page without playing the animation
I don't really know how to make use of threading to tell the program such that after the animation
has played for 5 seconds, it will automatically direct the user to third page.
Please advice and help me. Thanks
PageOne.java
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class PageOne {
private JPanel panelCont = new JPanel();
private JButton btn1 = new JButton("btn 1");
private JPanel panelFirst = new JPanel();
private JPanel panelSecond = new JPanel();
private JPanel panelThird = new JPanel();
private CardLayout c1 = new CardLayout();
private JFrame frame = new JFrame();
public PageOne() {
panelCont.setLayout(c1);
panelSecond.add(new PageTwo());
panelThird.add(new PageThree());
panelFirst.add(btn1);
panelCont.add(panelFirst,"1");
panelCont.add(panelSecond,"2");
panelCont.add(panelThird,"3");
c1.show(panelCont, "1");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
if(t1.getState() == Thread.State.RUNNABLE) {
c1.show(panelCont, "2");
}
System.out.println(t1.getState());
if(t1.getState() == Thread.State.TIMED_WAITING) {
c1.show(panelCont, "3");
}
}
});
frame.add(panelCont);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setSize(400,600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new PageOne();
}
});
}
}
PageTwo.java
import java.awt.BorderLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class PageTwo extends JPanel {
public PageTwo() {
setLayout(new BorderLayout());
Icon icon = new ImageIcon("animation.gif");
JLabel label = new JLabel(icon);
add(label);
}
}
PageThree.java
import javax.swing.JLabel;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class PageThree extends JPanel {
public PageThree() {
JLabel label = new JLabel("This is Page 3");
add(label);
}
}