⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 counter.java

📁 《JAVA程序设计教程》这本书的所有源代码
💻 JAVA
字号:
//Counter.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Counter
{
	public static void main(String[] args)
	{
		JFrame frame=new CounterFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.show();
	}
}

class CounterFrame extends JFrame
{
	public static final int WIDTH = 250;
	public static final int HEIGHT = 150;
//记数显示文本。
	private TextField textField = new TextField(20);
	
	public CounterFrame()
	{
		setSize(WIDTH, HEIGHT);
		setTitle("Counter");
		Container contentPane = getContentPane();

		JPanel textPanel = new JPanel();
		textPanel.add(textField);

//开始记数的按钮。
		JPanel buttonPanel = new JPanel();
		addButton(buttonPanel, "Start",
			new ActionListener()
			{
				public void actionPerformed(ActionEvent evt)
				{
					addCounter();
				}
			}
		);

//停止记数的按钮,并退出程序。
		addButton(buttonPanel, "Close",
			new ActionListener()
			{
				public void actionPerformed(ActionEvent evt)
				{
					System.exit(0);
				}
			}
		);

		contentPane.add(textPanel, BorderLayout.NORTH);
		contentPane.add(buttonPanel, BorderLayout.SOUTH);
	}

	public void addButton(Container c, String title, ActionListener 
							listener)
	{
		JButton button = new JButton(title);
		c.add(button);
		button.addActionListener(listener);
	}

	public void addCounter()
	{
//循环50次,每次递增1。
		for (int i = 0; i < 50; i++)
		{
			try
			{
				textField.setText(Integer.toString(i));
//暂时停止当前线程50毫秒。
				Thread.sleep(50);
			}
			catch (InterruptedException e)
			{
			}
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -