極簡版秒錶(java GUI)
阿新 • • 發佈:2018-11-29
package javaPractice; import javax.swing.*; import java.text.*; import java.util.*; import java.awt.*; import java.awt.event.*; public class Stopwatch { public static void main(String[] args) { new Timer(); } } class Timer extends JFrame{ JLabel jl; JTextField jt1,jt2; JButton jb; SimpleDateFormat df; private static TimeNow thread; Timer(){ this.setSize(400,300);//初始化視窗 this.setTitle("Stopwatch"); this.setLayout(null); df = new SimpleDateFormat("hh:mm:ss");//設定時間格式 jt1 = new JTextField();//例項化元件 jt2 = new JTextField(); jb = new JButton("Current time"); jt1.setText(df.format(new Date())); jt1.setBounds(105,50,120,35);//定義各元件的顯示位置和大小 jb.setBounds(90,110,150,30); jt2.setBounds(105,170,120,35); this.add(jt1);//把現有元件新增到窗體視窗 this.add(jb); this.add(jt2); this.setLocationRelativeTo(null);//視窗居中顯示 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); thread = new TimeNow(); jb.addActionListener(new ButtonListener()); } class TimeNow implements Runnable{ public void run() { while(true) { jt1.setText(df.format(new Date())); try { Thread.sleep(1); }catch(InterruptedException e) { e.printStackTrace(); System.exit(1); } } } public void start() { jt2.setText(df.format(new Date())); } } class ButtonListener implements ActionListener{ JPanel jp = new JPanel(); public void actionPerformed(ActionEvent e) { thread.start(); } } }