Thread.sleep()无法正常工作

时间:2017-04-14 15:03:54

标签: java oop

我是java的初学者,我一直在尝试实现Thread.sleep()但它似乎无法正常工作。我已经包含了运行的程序,可以正确测试。这只是我实际制作的实际程序的重新创建版本。我用更少的代码使其变得更简单

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Color;

public class test extends JFrame implements ActionListener {


private JButton btnHideTable ;
private JLabel initial;
private JLabel second;
private JLabel last;

/**
 * Launch the application.
 */
public static void main(String[] args) {

    test window = new test();
    window.setVisible(true);
}

/**
 * Create the application.
 */
public test() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {

    setTitle("Testing");
    setSize(700,400);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);




            btnHideTable = new JButton("HIDE TABLE");
            btnHideTable.setBounds(233, 76, 193, 36);
            btnHideTable.setFont(new Font("Tahoma", Font.PLAIN, 16));
            getContentPane().add(btnHideTable);

            initial = new JLabel("INITIAL");
            initial.setHorizontalAlignment(SwingConstants.CENTER);
            initial.setFont(new Font("Trebuchet MS", Font.PLAIN, 24));
            initial.setBounds(202, 136, 269, 57);
            getContentPane().add(initial);

            second = new JLabel("SECOND");
            second.setHorizontalAlignment(SwingConstants.CENTER);
            second.setForeground(Color.MAGENTA);
            second.setFont(new Font("Tahoma", Font.PLAIN, 34));
            second.setBounds(233, 203, 250, 65);
            getContentPane().add(second);

            last = new JLabel("LAST");
            last.setForeground(Color.GREEN);
            last.setHorizontalAlignment(SwingConstants.CENTER);
            last.setFont(new Font("Traditional Arabic", Font.PLAIN, 45));
            last.setBounds(220, 279, 255, 71);
            getContentPane().add(last);

            btnHideTable.addActionListener(this);

            // Both these labels are not visible when the window launches
            second.setVisible(false);
            last.setVisible(false);
}

@Override
public void actionPerformed(ActionEvent ae) {
    if(ae.getSource() == btnHideTable){

        // When button is clicked, i want the initial label to be invisible and the secon label be visible

        initial.setVisible(false); //THIS WORKS FINE
        second.setVisible(true); // THIS DOESN'T WORK AS IT SHOULD BECAUSE IT DOESN'T SHOW

        //After 5 seconds, display the last Labe
        try {
            Thread.sleep(5000);
            last.setVisible(true);
            second.setVisible(false);
        } catch (InterruptedException e) {
            e.getMessage();
            e.printStackTrace();
        }

    }
    }

}

0 个答案:

没有答案