Java爬蟲_爬蟲項(xiàng)目

一:介紹:本文會(huì)介紹一個(gè)完整的爬蟲項(xiàng)目,并打包成windows可執(zhí)行程序
1.1、效果圖:


image.png

1.2、抓取數(shù)據(jù)頁面:


image.png

1.3、抓取結(jié)果:
image.png

二:開發(fā):
2.1、創(chuàng)建一個(gè)Maven項(xiàng)目“demo”
2.2、pom.xml中添加項(xiàng)目依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cll</groupId>
    <artifactId>demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.htmlunit</groupId>
            <artifactId>htmlunit</artifactId>
            <version>2.27</version>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.8.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.10.1</version>
        </dependency>
        <dependency>
            <groupId>com.hynnet</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6.12.1</version>
        </dependency>
    </dependencies>
</project>

2.3、創(chuàng)建如下類

1`、QYEmailHelper.java(爬取網(wǎng)頁數(shù)據(jù)的主要工具類)
import CaililiangTools.ConfigHelper;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;

public class QYEmailHelper {
    static WebClient webClient=new WebClient(BrowserVersion.CHROME);
    ArrayList<HashMap<String,String>> returnList = new ArrayList<HashMap<String,String>>();
    static String baseUrl ="";
    static  int num =1;
    ConfigHelper configHelper = new ConfigHelper();
    Properties properties=null;

    //瀏覽器初始化
    public void WebClientInit(){
        webClient.getCookieManager().setCookiesEnabled(true);//設(shè)置cookie是否可用
        webClient.getOptions().setActiveXNative(false);
        webClient.getOptions().setRedirectEnabled(true);// 啟動(dòng)客戶端重定向
        webClient.getOptions().setCssEnabled(false);//禁用Css,可避免自動(dòng)二次請(qǐng)求CSS進(jìn)行渲染
        webClient.getOptions().setJavaScriptEnabled(true); // 啟動(dòng)JS
        webClient.getOptions().setUseInsecureSSL(true);//忽略ssl認(rèn)證
        webClient.getOptions().setThrowExceptionOnScriptError(false);//運(yùn)行錯(cuò)誤時(shí),不拋出異常
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());// 設(shè)置Ajax異步
        webClient.getOptions().setMaxInMemory(50000);
        properties = configHelper.getEmailUserInfos();
    }

    public void closeWebClient(){
        webClient.close();
        webClient=new WebClient(BrowserVersion.CHROME);
    }

    //用戶登錄并返回收件箱的地址
    public String UserLogin(String url,String name,String password) throws Exception{
        url = url.replace("param=caill@primeton.com","param="+name);
        final HtmlPage page = webClient.getPage(url);
        System.err.println("查詢中,請(qǐng)稍候");
        //TimeUnit.SECONDS.sleep(3);  //web請(qǐng)求數(shù)據(jù)需要時(shí)間,必須讓主線程休眠片刻
        HtmlForm form=page.getForms().get(0);
        HtmlPasswordInput txtPwd = (HtmlPasswordInput)form.getInputByName("pp");//密碼框
        txtPwd.setValueAttribute(password);//設(shè)置密碼
        HtmlSubmitInput submit=(HtmlSubmitInput) form.getInputByValue("登錄");
        final HtmlPage page2 = (HtmlPage) submit.click();//登錄進(jìn)入
        DomElement e =page2.getElementById("folder_1");
        HtmlPage page3 = webClient.getPage("https://mail.primeton.com"+e.getAttribute("href"));
        //TimeUnit.SECONDS.sleep(3);  //web請(qǐng)求數(shù)據(jù)需要時(shí)間,必須讓主線程休眠片刻
        HtmlInlineFrame frame1 = (HtmlInlineFrame)page3.getElementById("mainFrame");
        String src = frame1.getAttribute("src");
        baseUrl="https://mail.primeton.com"+src;
        return "https://mail.primeton.com"+src;
    }

    //抓取Url中的數(shù)據(jù)
    public long getHtmlPage(String url,long startTime,long endTime) throws Exception{
        HashMap<String,String> returnMap = new HashMap<String,String>();
        long endTime2=0L;
        HtmlPage page = webClient.getPage(url);
        HtmlBody tbody = (HtmlBody) page.getBody();
        DomNodeList<HtmlElement> lists = tbody.getElementsByTagName("table");
        //System.out.println( page.asXml());
        for(HtmlElement he:lists){
            long time =0L;
            HashMap<String,String> results = new HashMap<String,String>();
            String xml = he.asXml();
            if(xml.startsWith("<table cellspacing=\"0\" class=") && xml.contains("<input totime=")){
                Document document = Jsoup.parse(xml);
                Elements es = document.getElementsByClass("cx");
                Elements es2 = document.getElementsByClass("black");
                for(Element e :es){
                    Node node =e.childNode(1);
                    time = Long.parseLong(node.attr("totime"));
                    endTime2 = time;
                    String email = node.attr("fa");
                    if(properties.containsKey(email)){
                        String value = properties.getProperty(email);
                        String[] vs = value.split("@@");
                        if(vs.length==2){
                            results.put("totime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time)));
                            results.put("unread",(node.attr("unread")).equalsIgnoreCase("true")?"已讀":"未讀");
                            results.put("name",vs[1]);
                            results.put("mail",email);
                            results.put("dept",vs[0]);
                        }else{
                            results.put("totime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time)));
                            results.put("unread",(node.attr("unread")).equalsIgnoreCase("true")?"已讀":"未讀");
                            results.put("name",node.attr("fn"));
                            results.put("mail",email);
                            results.put("dept","");
                        }
                    }else{
                        results.put("totime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time)));
                        results.put("unread",(node.attr("unread")).equalsIgnoreCase("true")?"已讀":"未讀");
                        results.put("name",node.attr("fn"));
                        results.put("mail",email);
                        results.put("dept","");
                    }
                }
                for(Element e :es2){
                    results.put("title",e.ownText());
                }
                if(time<=endTime && startTime<=time){
                    returnList.add(results);
                }
            }
        };
        return endTime2;
    }

    public void grabData(String url,long startTime,long endTime) throws Exception{
        long endTime2 = getHtmlPage(url,startTime,endTime);
        if(endTime2>startTime){
            String nextPageUrl=baseUrl.replace("page=0","page="+num);
            num++;
            grabData(nextPageUrl,startTime,endTime);
        }
    }

    public int exportData(long startTime,long endTime,String name,String password){
        int returnInt = 0;
        this.WebClientInit();
        String webUrl="https://mail.primeton.com/cgi-bin/loginpage?t=logindomain&s=logout&f=biz&param=caill@primeton.com";
        String url1 = null;
        try {
            url1 = this.UserLogin(webUrl,name,password);
            grabData(url1,startTime,endTime);
            ExcelHelper excelHelper = new ExcelHelper();
            excelHelper.exportExcel(this.returnList);
            num=1;
            baseUrl ="";
            returnList = new ArrayList<HashMap<String,String>>();
            closeWebClient();
        } catch (Exception e) {
            returnInt = 1;
            num=1;
            baseUrl ="";
            returnList = new ArrayList<HashMap<String,String>>();
            closeWebClient();
        }
        return returnInt;
    }
}

2、ExcelHelper.java(導(dǎo)出Excel文件的主要工具類)
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

public class ExcelHelper {
    public void exportExcel(ArrayList<HashMap<String,String>> list){
        String dbname = "";
        String path =null;

        String row = "部門,姓名,郵箱,時(shí)間,是否閱讀,主題";
        String[] rows = row.split(",");
        ArrayList fields = null;
        ArrayList data = new ArrayList();
        ArrayList heard = new ArrayList();
        ArrayList datas = new ArrayList();
        for(String r:rows){
            data.add(r);
        }
        datas.add(data);

        for(HashMap<String,String> hm:list){
            ArrayList data2 = new ArrayList();
            data2.add(hm.get("dept"));
            data2.add(hm.get("name"));
            data2.add(hm.get("mail"));
            data2.add(hm.get("totime"));
            data2.add(hm.get("unread"));
            data2.add(hm.get("title"));
            datas.add(data2);
        }

        FileSystemView fsv = FileSystemView.getFileSystemView();
        File f=fsv.getHomeDirectory(); //這便是讀取桌面路徑的方法了
        path = f.getPath();
        System.out.println(path);
        OutputStream out = null ; // 準(zhǔn)備好一個(gè)輸出的對(duì)象
        if(!f.exists()){f.mkdir();}
        String filePath = path+"/周報(bào)上報(bào)情況"+new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss").format(new Date(System.currentTimeMillis()))+".xls";
        File outFile = new File(filePath);
        try {
            out = new FileOutputStream(filePath); // 通過對(duì)象多態(tài)性,進(jìn)行實(shí)例化
            // 創(chuàng)建Excel工作薄
            WritableWorkbook workbook = Workbook.createWorkbook(out);

            int length = datas.size();

            // 添加第一個(gè)工作表并設(shè)置第一個(gè)Sheet的名字
            WritableSheet sheet = workbook.createSheet("周報(bào)詳情", 1);
            Label label;
            heard=(ArrayList)datas.get(0);
            for(int i2 = 0;i2<heard.size();i2++){
                //String aaaaaaa= (heard.get(i2)).toString();
                label = new Label(i2,0,(String) heard.get(i2));
                sheet.addCell(label);
            }
            ArrayList filed = new ArrayList();

            for(int i3=1;i3<length;i3++){
                filed = (ArrayList)datas.get(i3);
                for(int i4 = 0;i4<filed.size();i4++){
                    label = new Label(i4,i3,(String) filed.get(i4));
                    sheet.addCell(label);
                }
            }

            // 寫入數(shù)據(jù)
            workbook.write();
            // 關(guān)閉文件
            workbook.close();
            out.close();

        } catch (Exception  e) {
            e.printStackTrace();
        }
    }
}

3、MyFrame.java(widows窗口類)
import CaililiangTools.ConfigHelper;
import DateSelector.DateSelector;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

public class MyFrame extends JFrame{
    ConfigHelper confighelper = new ConfigHelper();

    JPanel panel = new JPanel();
    JTextField name = new JTextField();
    JPasswordField password = new JPasswordField();
    JButton startDate = new DateSelector();
    JButton endDate = new DateSelector();
    JButton button1 = new JButton("一鍵導(dǎo)出");
    JLabel label = new JLabel("提示:導(dǎo)出數(shù)據(jù)需要一些時(shí)間,勿頻繁點(diǎn)擊按鈕");
    JButton button2 = new JButton("幫助");
    int width = Toolkit.getDefaultToolkit().getScreenSize().width;
    int height =Toolkit.getDefaultToolkit().getScreenSize().height;
    public MyFrame(){
        this.setTitle("普元企業(yè)郵箱助手");
        this.setSize(355,340);
        this.setResizable(false);
        this.setLocation(width/2-176,height/2-170);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.add(panel);
        panel.setLayout(null);
        JLabel label1 = new JLabel("賬號(hào):");
        JLabel label2 = new JLabel("密碼:");
        JLabel label3 = new JLabel("開始時(shí)間:");
        JLabel label4 = new JLabel("截止時(shí)間:");
        label1.setBounds(10,20,80,25);
        label2.setBounds(10,70,80,25);
        label3.setBounds(10,120,80,25);
        label4.setBounds(10,170,80,25);
        panel.add(label1);
        panel.add(label2);
        panel.add(label3);
        panel.add(label4);
        name.setBounds(100,20,240,25);
        password.setBounds(100,70,240,25);
        startDate.setBounds(100,120,240,25);
        endDate.setBounds(100,170,240,25);
        panel.add(name);
        panel.add(password);
        panel.add(startDate);
        panel.add(endDate);
        HashMap<String,String> user = confighelper.getUserInfo();
        name.setText(user.get("userName"));
        password.setText(user.get("passWord"));
        button1.setBounds(115,220,100,30);
        button1.setBackground(Color.CYAN);
        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy年MM月dd日   HH時(shí)mm分ss秒");
                String name2 = name.getText();
                String password2 = password.getText();
                long startTime = 0L;
                long endTime = 0L;
                try {
                    Date date1=sDateFormat.parse(startDate.getText());
                    Date date2=sDateFormat.parse(endDate.getText());
                    startTime = date1.getTime();
                    endTime = date2.getTime();
                } catch(ParseException px) {
                    px.printStackTrace();
                }
                try {
                    QYEmailHelper helper = new QYEmailHelper();
                    int out = helper.exportData(startTime,endTime,name2,password2);
                    if(out==1){
                        label.setText("賬號(hào)密碼錯(cuò)誤,無法登陸");
                    }else{
                        label.setText("數(shù)據(jù)導(dǎo)出成功");
                    }
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        });
        panel.add(button1);
        label.setBounds(10,270,300,30);
        panel.add(label);
        button2.setBounds(285,270,60,30);
        panel.add(button2);
        button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFrame frame1 = new JFrame("幫助手冊(cè)");
                frame1.setSize(355,340);
                frame1.setResizable(false);
                frame1.setLocation(width/2+176,height/2);
                JTextArea jta = new JTextArea(10, 15);
                jta.setTabSize(4);
                jta.setFont(new Font("宋體", Font.PLAIN, 16));
                jta.setLineWrap(true);// 激活自動(dòng)換行功能
                jta.setWrapStyleWord(false);// 激活斷行不斷字功能
                jta.setText("本工具使用注意事項(xiàng):   \n1、UserInfo.properties文件和EmaiUserInfos.properties文件必須放在windows桌面才生效;\n2、UserInfo.properties文件存放的是登錄人信息,有該文件之后每次啟動(dòng)程序可以不用輸賬號(hào)密碼;  \n3、EmaiUserInfos.properties文件存放的是郵箱聯(lián)系人的信息,可以輔助組裝數(shù)據(jù);  \n4、導(dǎo)出數(shù)據(jù)需要一些時(shí)間,切勿頻繁點(diǎn)擊'一鍵導(dǎo)出'按鈕,否則可能導(dǎo)致死機(jī);  \n5、如有其它問題請(qǐng)聯(lián)系微信(caililiangcaililiang)或郵箱(caill@primeton.com)");
                //jta.setBackground(Color.pink);
                frame1.add(jta);
                frame1.setVisible(true);
            }
        });

        this.setVisible(true);
    }
}

4、MyEntrance.java(程序入口類)
public class MyEntrance {
    public static void main(String[] args){
        new MyFrame();
    }
}

5、DateSelector.java(windows窗口中的日期選擇控件)
package DateSelector;

import java.util.Date;
import java.util.Calendar;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.awt.Dimension;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Frame;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent; //import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.JSpinner.NumberEditor;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import javax.swing.border.LineBorder;


public class DateSelector extends JButton {


      private DateChooser dateChooser = null;


      private String preLabel = "";


      public DateSelector() {
            this(getNowDate());
      }


      public DateSelector(SimpleDateFormat df, String dateString) {
            this();
            setText(df, dateString);
      }


      public DateSelector(Date date) {
            this("", date);
      }


      public DateSelector(String preLabel, Date date) {
            if (preLabel != null)
                  this.preLabel = preLabel;
            setDate(date);
            setBorder(null);
            setCursor(new Cursor(Cursor.HAND_CURSOR));
            super.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent e) {
                        if (dateChooser == null)
                              dateChooser = new DateChooser();
                        Point p = getLocationOnScreen();
                        p.y = p.y + 30;
                        dateChooser.showDateChooser(p);
                  }
            });
      }


      private static Date getNowDate() {
            return Calendar.getInstance().getTime();
      }


      private static SimpleDateFormat getDefaultDateFormat() {
            return new SimpleDateFormat("yyyy年MM月dd日   HH時(shí)mm分ss秒");
      }


      public void setText(String s) {
            Date date;
            try {
                  date = getDefaultDateFormat().parse(s);
            } catch (ParseException e) {
                  date = getNowDate();
            }
            setDate(date);
      }


      public void setText(SimpleDateFormat df, String s) {
            Date date;
            try {
                  date = df.parse(s);
            } catch (ParseException e) {
                  date = getNowDate();
            }
            setDate(date);
      }


      public void setDate(Date date) {
            super.setText(preLabel + getDefaultDateFormat().format(date));
      }


      public Date getDate() {
            String dateString = getText().substring(preLabel.length());
            try {
                  return getDefaultDateFormat().parse(dateString);
            } catch (ParseException e) {
                  return getNowDate();
            }


      }


      // 覆蓋父類的方法使之無效
              public void addActionListener(ActionListener listener) {
      }


      private class DateChooser extends JPanel implements ActionListener,
                  ChangeListener {
            int startYear = 1980; // 默認(rèn)【最小】顯示年份
            int lastYear = 2050; // 默認(rèn)【最大】顯示年份
            int width = 200; // 界面寬度
            int height = 200; // 界面高度


            Color backGroundColor = Color.gray; // 底色
            // 月歷表格配色----------------//
            Color palletTableColor = Color.white; // 日歷表底色
            Color todayBackColor = Color.orange; // 今天背景色
            Color weekFontColor = Color.blue; // 星期文字色
            Color dateFontColor = Color.black; // 日期文字色
            Color weekendFontColor = Color.red; // 周末文字色


            // 控制條配色------------------//
            Color controlLineColor = Color.blue; // 控制條底色
            Color controlTextColor = Color.white; // 控制條標(biāo)簽文字色


            Color rbFontColor = Color.white; // RoundBox文字色
            Color rbBorderColor = Color.red; // RoundBox邊框色
            Color rbButtonColor = Color.pink; // RoundBox按鈕色
            Color rbBtFontColor = Color.red; // RoundBox按鈕文字色


            JDialog dialog;
            JSpinner yearSpin;
            JSpinner monthSpin;
            JSpinner hourSpin;
            JSpinner minuteSpin;
            JSpinner secondSpin;
            JButton[][] daysButton = new JButton[6][7];


            DateChooser() {


                  setLayout(new BorderLayout());
                  setBorder(new LineBorder(backGroundColor, 2));
                  setBackground(backGroundColor);


                  /*上中下布局*/
                  JPanel topYearAndMonth = createYearAndMonthPanal();
                  add(topYearAndMonth, BorderLayout.NORTH);
                  JPanel centerWeekAndDay = createWeekAndDayPanal();
                  add(centerWeekAndDay, BorderLayout.CENTER);
                  JPanel southMinAndSec = createMinuteAndsecondPanal();
                  add(southMinAndSec, BorderLayout.SOUTH);
            }


            private JPanel createYearAndMonthPanal() {
                  Calendar c = getCalendar();
                  int currentYear = c.get(Calendar.YEAR);//年
                  int currentMonth = c.get(Calendar.MONTH) + 1;//月


                  JPanel result = new JPanel();
                  result.setLayout(new FlowLayout());
                  result.setBackground(controlLineColor);


                  yearSpin = new JSpinner(new SpinnerNumberModel(currentYear,
                                                  startYear, lastYear, 1));
                  yearSpin.setPreferredSize(new Dimension(48, 20));
                  yearSpin.setName("Year");
                  yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));
                  yearSpin.addChangeListener(this);
                  result.add(yearSpin);


                  JLabel yearLabel = new JLabel("年");
                  yearLabel.setForeground(controlTextColor);
                  result.add(yearLabel);


                  monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1,
                                                  12, 1));
                  monthSpin.setPreferredSize(new Dimension(35, 20));
                  monthSpin.setName("Month");
                  monthSpin.addChangeListener(this);
                  result.add(monthSpin);


                  JLabel monthLabel = new JLabel("月");
                  monthLabel.setForeground(controlTextColor);
                  result.add(monthLabel);


                  return result;
            }


            private JPanel createWeekAndDayPanal() {
                  String colname[] = { "日", "一", "二", "三", "四", "五", "六" };
                  JPanel result = new JPanel();
                  // 設(shè)置固定字體,以免調(diào)用環(huán)境改變影響界面美觀
                  result.setFont(new Font("宋體", Font.PLAIN, 12));
                  result.setLayout(new GridLayout(7, 7));
                  result.setBackground(Color.white);
                  JLabel cell;


                  for (int i = 0; i < 7; i++) {
                        cell = new JLabel(colname[i]);
                        cell.setHorizontalAlignment(JLabel.RIGHT);
                        if (i == 0 || i == 6)
                              cell.setForeground(weekendFontColor);
                        else
                              cell.setForeground(weekFontColor);
                        result.add(cell);
                  }


                  int actionCommandId = 0;
                  for (int i = 0; i < 6; i++)
                        for (int j = 0; j < 7; j++) {
                              JButton numberButton = new JButton();
                              numberButton.setBorder(null);
                              numberButton.setHorizontalAlignment(SwingConstants.RIGHT);
                              numberButton.setActionCommand(String
                                                                  .valueOf(actionCommandId));
                              numberButton.addActionListener(this);
                              numberButton.setBackground(palletTableColor);
                              numberButton.setForeground(dateFontColor);
                              if (j == 0 || j == 6)
                                    numberButton.setForeground(weekendFontColor);
                              else
                                    numberButton.setForeground(dateFontColor);
                              daysButton[i][j] = numberButton;
                              result.add(numberButton);
                              actionCommandId++;
                        }


                  return result;
            }


            private JPanel createMinuteAndsecondPanal() {
                  Calendar c = getCalendar();


                  int currentHour = c.get(Calendar.HOUR_OF_DAY);//時(shí)
                  int currentMin = c.get(Calendar.MINUTE);//分
                  int currentSec = c.get(Calendar.SECOND);//秒


                  JPanel result = new JPanel();
                  result.setLayout(new FlowLayout());
                  result.setBackground(controlLineColor);


                  hourSpin = new JSpinner(new SpinnerNumberModel(currentHour, 0, 23,1));
                  hourSpin.setPreferredSize(new Dimension(35, 20));
                  hourSpin.setName("Hour");
                  hourSpin.addChangeListener(this);
                  result.add(hourSpin);


                  JLabel hourLabel = new JLabel("時(shí)");
                  hourLabel.setForeground(controlTextColor);
                  result.add(hourLabel);
                   
                  minuteSpin = new JSpinner(new SpinnerNumberModel(currentMin, 0, 59, 1));
                  minuteSpin.setPreferredSize(new Dimension(35, 20));
                  minuteSpin.setName("Minute");
                  minuteSpin.addChangeListener(this);
                  result.add(minuteSpin);


                  JLabel minuteLabel = new JLabel("分");
                  minuteLabel.setForeground(controlTextColor);
                  result.add(minuteLabel);
                   
                  secondSpin = new JSpinner(new SpinnerNumberModel(currentSec, 0, 59,1));
                  secondSpin.setPreferredSize(new Dimension(35, 20));
                  secondSpin.setName("Second");
                  secondSpin.addChangeListener(this);
                  result.add(secondSpin);


                  JLabel secondLabel = new JLabel("秒");
                  secondLabel.setForeground(controlTextColor);
                  result.add(secondLabel);


                  return result;
            }
             
            private JDialog createDialog(Frame owner) {
                  JDialog result = new JDialog(owner, "日期時(shí)間選擇", true);
                  result.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
                  result.getContentPane().add(this, BorderLayout.CENTER);
                  result.pack();
                  result.setSize(width, height);
                  return result;
            }


            void showDateChooser(Point position) {
                  Frame owner = (Frame) SwingUtilities
                              .getWindowAncestor(DateSelector.this);
                  if (dialog == null || dialog.getOwner() != owner)
                        dialog = createDialog(owner);
                  dialog.setLocation(getAppropriateLocation(owner, position));
                  flushWeekAndDay();
                  dialog.show();
            }


            Point getAppropriateLocation(Frame owner, Point position) {
                  Point result = new Point(position);
                  Point p = owner.getLocation();
                  int offsetX = (position.x + width) - (p.x + owner.getWidth());
                  int offsetY = (position.y + height) - (p.y + owner.getHeight());


                  if (offsetX > 0) {
                        result.x -= offsetX;
                  }


                  if (offsetY > 0) {
                        result.y -= offsetY;
                  }


                  return result;


            }


            private Calendar getCalendar() {
                  Calendar result = Calendar.getInstance();
                  result.setTime(getDate());
                  return result;
            }


            private int getSelectedYear() {
                  return ((Integer) yearSpin.getValue()).intValue();
            }


            private int getSelectedMonth() {
                  return ((Integer) monthSpin.getValue()).intValue();
            }


            private int getSelectedHour() {
                  return ((Integer) hourSpin.getValue()).intValue();
            }
             
            private int getSelectedMinute() {
                  return ((Integer) minuteSpin.getValue()).intValue();
            }
             
            private int getSelectedSecond() {
                  return ((Integer) secondSpin.getValue()).intValue();
            }


            private void dayColorUpdate(boolean isOldDay) {
                  Calendar c = getCalendar();
                  int day = c.get(Calendar.DAY_OF_MONTH);
                  c.set(Calendar.DAY_OF_MONTH, 1);
                  int actionCommandId = day - 2 + c.get(Calendar.DAY_OF_WEEK);
                  int i = actionCommandId / 7;
                  int j = actionCommandId % 7;
                  if (isOldDay)
                        daysButton[i][j].setForeground(dateFontColor);
                  else
                        daysButton[i][j].setForeground(todayBackColor);
            }


            private void flushWeekAndDay() {
                  Calendar c = getCalendar();
                  c.set(Calendar.DAY_OF_MONTH, 1);
                  int maxDayNo = c.getActualMaximum(Calendar.DAY_OF_MONTH);
                  int dayNo = 2 - c.get(Calendar.DAY_OF_WEEK);
                  for (int i = 0; i < 6; i++) {
                        for (int j = 0; j < 7; j++) {
                              String s = "";
                              if (dayNo >= 1 && dayNo <= maxDayNo)
                                    s = String.valueOf(dayNo);
                              daysButton[i][j].setText(s);
                              dayNo++;
                        }
                  }
                  dayColorUpdate(false);
            }


            public void stateChanged(ChangeEvent e) {
                  JSpinner source = (JSpinner) e.getSource();
                  Calendar c = getCalendar();
                  if (source.getName().equals("Hour")) {
                        c.set(Calendar.HOUR_OF_DAY, getSelectedHour());
                        setDate(c.getTime());
                        return;
                  }
                  else if(source.getName().equals("Minute")){
                  c.set(Calendar.MINUTE, getSelectedMinute());
                        setDate(c.getTime());
                        return;
                  }
                  else if(source.getName().equals("Second")){
                  c.set(Calendar.SECOND, getSelectedSecond());
                        setDate(c.getTime());
                        return;
                  }


                  dayColorUpdate(true);


                  if (source.getName().equals("Year"))
                        c.set(Calendar.YEAR, getSelectedYear());
                  else
                        // (source.getName().equals("Month"))
                        c.set(Calendar.MONTH, getSelectedMonth() - 1);
                  setDate(c.getTime());
                  flushWeekAndDay();
            }


            public void actionPerformed(ActionEvent e) {
                  JButton source = (JButton) e.getSource();
                  if (source.getText().length() == 0) return;
                  dayColorUpdate(true);
                  source.setForeground(todayBackColor);
                  int newDay = Integer.parseInt(source.getText());
                  Calendar c = getCalendar();
                  c.set(Calendar.DAY_OF_MONTH, newDay);
                  setDate(c.getTime());
            }


      }


}

6、ConfigHelper.java(配置文件獲取類)
package CaililiangTools;

import java.io.*;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Properties;

public class ConfigHelper {
    public HashMap<String,String> getUserInfo() {
        HashMap<String,String> returnMap = new HashMap<String,String>();
        try{
            Properties properties = new Properties();
            InputStream in = new BufferedInputStream(new FileInputStream("C:\\Users\\Administrator\\Desktop\\UserInfo.properties"));
            properties.load(new InputStreamReader(in, "utf-8"));
            String userName = properties.getProperty("userName");
            String passWord = properties.getProperty("passWord");
            returnMap.put("userName",userName);
            returnMap.put("passWord",passWord);
        }catch (IOException e){
            System.err.println("UserInfo.properties文件讀取失敗");
            System.err.println("UserInfo.properties文件必須放在windows桌面上");
        }
        return returnMap;
    }
    public Properties getEmailUserInfos() {
        Properties properties=null;
        HashMap<String,String> returnMap = new HashMap<String,String>();
        try{
            properties = new Properties();
            InputStream in =  new BufferedInputStream(new FileInputStream("C:\\Users\\Administrator\\Desktop\\EmaiUserInfos.properties"));
            properties.load(new InputStreamReader(in, "utf-8"));
        }catch (IOException e){
            System.err.println("EmaiUserInfos.properties文件讀取失敗");
            System.err.println("EmaiUserInfos.properties文件必須放在windows桌面上");
        }
        return properties;
    }
}

項(xiàng)目結(jié)構(gòu)圖:


image.png

三、項(xiàng)目導(dǎo)出可執(zhí)行jar包
3.1、setting配置


image.png
image.png
image.png
image.png

3.2、編譯


image.png
image.png
image.png

四、jar包裝成EXE可執(zhí)行程序(exe4j工具)
參照我的另一篇文章:http://www.itdecent.cn/p/bfad27d7812d

五、exe文件打包成可安裝程序(inno setup工具)
參照我的另一篇文章:http://www.itdecent.cn/p/63b2605ee2b4

六、項(xiàng)目下載地址:
鏈接:https://pan.baidu.com/s/18mhhNw1qJ2yQVKX9rZamdQ
提取碼:l7jz

如有問題或有想相互學(xué)習(xí)交流的,可以聯(lián)系本人(郵箱:18986837482@163.com,微信:caililiangcaililiang,QQ:785553790)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容