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

📄 internettimepanel.java

📁 本次实验中用Java实现的Calendar具有跨平台运行能力
💻 JAVA
字号:
/**
 * 
 */
package edu.swjtu.sist.java.calendar;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;

import sun.util.calendar.CalendarSystem;

/**
 * @author Lee
 *
 */
public class InternetTimePanel extends JPanel implements Runnable,
        ActionListener, ItemListener
{
    private Thread timer = null;

    private final static int DEFAULT_PORT = 37;

    //private final static int    DEFAULT_PORT = 13;
    private final static String DEFAULT_HOST = "time.nist.gov";

    private final static String WINDOWS_HOST = "time.windows.com";

    private String hostname = DEFAULT_HOST;

    private JButton updateButton = new JButton("立即更新(U)");

    private JComboBox timeServerBox = new JComboBox();

    private JCheckBox autoUpdateBox = new JCheckBox("自动与 Internet 时间服务器同步(S)");

    //protected Date timeFromServer;
    protected Calendar timeFromServer = Calendar.getInstance();

    //private JLabel updateMessage;
    private String updateMessage = "与服务器 " + DEFAULT_HOST + " 在 "
            + this.timeFromServer.getTime() + " 更新成功!";

    private JPanel c;

    public InternetTimePanel()
    {
        this.setLayout(new BorderLayout());
        this.timeServerBox.addItem(DEFAULT_HOST);
        this.timeServerBox.addItem(WINDOWS_HOST);
        JPanel n = new JPanel();
        n.setBackground(SystemColor.controlLtHighlight);

        n.setLayout(new GridLayout());
        n.add(this.autoUpdateBox);

        this.autoUpdateBox.setLocation(5, 2);
        this.autoUpdateBox.setSelected(true);
        this.autoUpdateBox.setBackground(SystemColor.controlLtHighlight);
        this.autoUpdateBox.addItemListener(this);

        this.add(n, BorderLayout.NORTH);

        c = new CenterPanel();
        JLabel lb = new JLabel("服务器:");

        lb.setBackground(SystemColor.controlLtHighlight);
        c.add(lb);
        c.add(this.timeServerBox);
        c.add(this.updateButton);
        /*
         JLabel la=new JLabel("                ");
         la.setBackground(SystemColor.controlLtHighlight);
         c.add(la);
         
         this.updateMessage=new JLabel("消息:");        
         updateMessage.setBackground(SystemColor.controlLtHighlight);
         c.add(updateMessage);*/
        //c.setBackground(SystemColor.controlLtHighlight);
        this.add(c, BorderLayout.CENTER);
        this.timeServerBox.addItemListener(this);
        this.updateButton.addActionListener(this);
        this.setBackground(SystemColor.controlLtHighlight);
        JLabel lc = new JLabel("     同步只能在你的计算机与 Internet 连接时才能使用。");
        lc.setBackground(SystemColor.controlLtHighlight);
        this.add(lc, BorderLayout.SOUTH);
        c.repaint();
    }

    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == this.updateButton)
        {
            this.updateButton.setEnabled(false);
            this.start();

        }

    }

    public void start() //启动线程
    {
        if (timer == null)
        {
            timer = new Thread(this);
            timer.start();
        }
    }

    private boolean updateTime()
    {
        boolean r = true;

        int port = DEFAULT_PORT;
        // 从Date类是从1970开始。而时间服务器是从1900年开始,这是要转换的差值
        long differenceBetweenEpochs = 2208988800L;

        // 如果你不习惯使用上面的魔法数字,那么请使用下面这段代码。
        // 时间服务器的时区为GMT+0:00

        /*
         * TimeZone gmt = TimeZone.getTimeZone("GMT"); Calendar epoch1900 =
         * Calendar.getInstance(gmt); epoch1900.set(1900, 01, 01, 00, 00, 00);
         * long epoch1900ms = epoch1900.getTime().getTime(); Calendar epoch1970 =
         * Calendar.getInstance(gmt); epoch1970.set(1970, 01, 01, 00, 00, 00);
         * long epoch1970ms = epoch1970.getTime().getTime();
         * 
         * long differenceInMS = epoch1970ms - epoch1900ms; long
         * differenceBetweenEpochs = differenceInMS/1000;
         */

        InputStream raw = null;
        try
        {
            Socket theSocket = new Socket(hostname, port);
            raw = theSocket.getInputStream();

            long secondsSince1900 = 0;
            for (int i = 0; i < 4; i++)
            {
                secondsSince1900 = (secondsSince1900 << 8) | raw.read();
            }

            long secondsSince1970 = secondsSince1900 - differenceBetweenEpochs;
            long msSince1970 = secondsSince1970 * 1000;
            this.timeFromServer.setTimeInMillis(msSince1970);

            System.out.println("It is " + timeFromServer + " at " + hostname);

        } // end try
        catch (UnknownHostException ex)
        {
            this.timer = null;
            this.updateMessage = "与服务器:" + this.hostname + " 连接失败!!";

            r = false;
        }
        catch (IOException ex)
        {
            this.timer = null;
            this.updateMessage = "与服务器:" + this.hostname + " 发生IO异常,更新失败!!";

            r = false;
        }
        finally
        {
            try
            {
                if (raw != null) raw.close();
            }
            catch (IOException ex)
            {
            }
            finally
            {
                raw = null;
            }
        }

        this.updateMessage = "与服务器 " + this.hostname + " 在 "
                + this.timeFromServer.getTime() + " 更新成功!";

        return r;
    }

    public void setSystemTime(Calendar c)
    {

        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH) + 1;//转换0-11的格式到1-12格式
        int date = c.get(Calendar.DATE);

        int hour = c.get(Calendar.HOUR_OF_DAY)
                - ((c.getTimeZone().getRawOffset()) / 3600000);//设置为标准日时间
        int minute = c.get(Calendar.MINUTE);
        int second = c.get(Calendar.SECOND);
        try
        {
            WindowsTime.setLocalTime(year, month, date, hour, minute, second);
        }
        catch (TimeOutException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void stop() //停止线程 
    {
        timer = null;
    }

    public void run()
    {
        while (timer != null)
        {
            if (this.updateTime())
            {
                this.setSystemTime(this.timeFromServer);
                timer = null;
            }

            try
            {
                Thread.sleep(300);
            }
            catch (InterruptedException e)
            {
            }

        }
        timer = null;
        this.c.repaint();

        this.updateButton.setEnabled(true);
    }

    public void itemStateChanged(ItemEvent e)
    {
        if (e.getSource() == this.autoUpdateBox)//是否选中自动更新
        {
            if (e.getStateChange() == ItemEvent.SELECTED)
            {
                this.timeServerBox.setEnabled(true);
                this.updateButton.setEnabled(true);
            }
            else
            {
                this.timeServerBox.setEnabled(false);
                this.updateButton.setEnabled(false);
            }

        }
        if (e.getSource() == this.timeServerBox)//选择时间服务器
        {
            if (((String) e.getItem()).equals(DEFAULT_HOST))
            {
                this.hostname = DEFAULT_HOST;
            }
            else
            {
                this.hostname = WINDOWS_HOST;
            }
        }

        c.setBackground(SystemColor.controlLtHighlight);
        ;

    }

    class CenterPanel extends JPanel
    {

        public void paintComponent(Graphics g)
        {
            Graphics2D g2 = (Graphics2D) g;
            g2.drawString(updateMessage, 10, 60);
            this.setBackground(SystemColor.controlLtHighlight);
        }
    }

}

⌨️ 快捷键说明

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