Java实现-倒计时

Java实现-倒计时_第1张图片

Java实现-倒计时_第2张图片

package my;

import javax.swing.SwingUtilities;

public class ButtonThread extends Thread
{

	
	
	@Override
	public void run() 
	{
		int n=5;
		while(n>0)
		{
			//更新界面,显示倒计时
			
			final String text=String.valueOf(n);
			
			SwingUtilities.invokeLater(()->{
				MyFrame.label.setText(text);
			});
			n=n-1;
			try {
				Thread.sleep(1000*1);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		}
		
		//结束后更新界面
		SwingUtilities.invokeLater(()->{
			MyFrame.label.setText("开心顺利");
			MyFrame.button.setEnabled(true);
		});
	}
	
}

 

package my;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class MyFrame extends JFrame
{
	public static JButton button=new JButton("开始");
	public static JLabel label=new JLabel();
	
	public MyFrame(String title)
	{
		super(title);
		
		//面板
		JPanel root=new JPanel();
		this.setContentPane(root);
		root.setLayout(new BorderLayout());

		root.add(button,BorderLayout.PAGE_START);
		root.add(label,BorderLayout.CENTER);
		
		//设置label
		label.setBackground(Color.white);
		label.setForeground(Color.RED);
		label.setFont(new Font("宋体",Font.PLAIN,80));
		label.setHorizontalAlignment(SwingConstants.CENTER);
		
		button.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {
				onButton();
			}
			
		});
	}
	
	private void onButton()
	{
		button.setEnabled(false);
		ButtonThread th=new ButtonThread();
		th.start();
	}
}
	
package my;
 
import java.awt.Container;
import java.awt.FlowLayout;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
 
public class MyDemo
{
	private static void createGUI()
	{
		// JFrame指一个窗口,构造方法的参数为窗口标题
		JFrame frame = new MyFrame("Demo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
				// 设置窗口的其他参数,如窗口大小
		frame.setSize(500, 300);
		
		// 显示窗口
		frame.setVisible(true);
	}
	
	public static void main(String[] args)
	{

		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run()
			{
				createGUI();
			}
		});
 
	}
}

 

你可能感兴趣的:(Java【渡劫】,Swing高级,Java,Swing(GUI)图形界面)