- Java code
import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.util.*;import java.text.*;public class ShutFrame implements ActionListener,KeyListener{ private JLabel label_1 = null; private JLabel label_2= null; private JLabel overTime = null; private JTextField HH = null; private JTextField mm = null; private JTextField ss = null; private JButton exit = null; private JButton hide = null; private JButton start = null; public ShutFrame(){ JFrame jf = new JFrame(); label_1 = new JLabel("请输入时,分,秒!"); label_2 = new JLabel("距离关机时间还有:"); overTime = new JLabel("在这里显示时间"); HH = new JTextField(3); mm = new JTextField(3); ss = new JTextField(3); exit = new JButton("退出"); hide = new JButton("占位"); start = new JButton("开始"); JPanel jp1= new JPanel(); JPanel jp2= new JPanel(); JPanel jp3= new JPanel(); jp1.add(label_1); jp1.add(HH); jp1.add(mm); jp1.add(ss); jp2.add(label_2); jp2.add(overTime); jp3.add(exit); jp3.add(hide); jp3.add(start); jf.setLayout(new GridLayout(3,1)); jf.add(jp1); jf.add(jp2); jf.add(jp3); jf.setBounds(200,200,250,200); hide.addActionListener(this); start.addActionListener(this); HH.addKeyListener(this); mm.addKeyListener(this); ss.addKeyListener(this); jf.addKeyListener(this); jf.setVisible(true); } public void actionPerformed(ActionEvent e){ //this.hide(); if(e.getSource() == start){ if(!HH.getText().trim().equals("")&&!mm.getText().trim().equals("")&&!ss.getText().trim().equals("")){ String H = HH.getText(); String m = mm.getText(); String s = ss.getText(); String time = H + ":" + m + ":" + s; while(true){ try{ Date d =new Date(); SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss"); String now = df.format(d); long CloseTime = df.parse(time).getTime(); long NowTime = df.parse(now).getTime(); long second = (CloseTime - NowTime)/1000; System.out.println("shut time is : " + CloseTime); System.out.println("shut time is : " + NowTime); System.out.println("away with shut time is : " + second); if(second == 0){ System.out.println("computer is shut down!"); break; } Thread.sleep(1000); }catch(Exception e1){ e1.printStackTrace(); } } }else{ System.out.println("请输入完整时间"); } } } public void keyTyped(KeyEvent e){ } public void keyPressed(KeyEvent e){ } public void keyReleased(KeyEvent e){ //System.out.println(e.getKeyCode()); } public static void main(String[] args){ ShutFrame s = new ShutFrame(); }}
------解决方案--------------------
1、在构造方法中需要添加 jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
2、修改while(true)
- Java code
new Thread(){ public void run(){ while(true){ //....... } }}.start();