SchoolCheckerUI.SchoolChecker.java Source code

Java tutorial

Introduction

Here is the source code for SchoolCheckerUI.SchoolChecker.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package SchoolCheckerUI;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.json.JSONException;

/**
 *
 * @author Rish Shadra
 */
public class SchoolChecker extends javax.swing.JFrame implements Runnable {

    public static final int VERSION = 4;
    String town = "";
    String URL = "";
    Settings s;

    /**
     * Creates new form SchoolCheckerUI
     */
    @Override
    public void run() { //Auto-refresh thread.
        while (true) {
            try {
                String st = Checker.check(town, URL);
                lblStatus.setText(st);
                if (st.equalsIgnoreCase("closed")) {
                    this.requestFocus();
                }
                // System.out.println("Fetching new data");
            } catch (IOException ex) {
                Logger.getLogger(SchoolChecker.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                Thread.sleep(60000);
            } catch (InterruptedException ex) {
                Logger.getLogger(SchoolChecker.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public SchoolChecker() {
        try {
            this.s = new Settings();
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(SchoolChecker.class.getName()).log(Level.SEVERE, null, ex);
        }
        initComponents();
        this.setTitle("Closings-v" + VERSION); //Initialize window things.
        this.setResizable(false);

        if (!s.isFirstRun) { //If first run NOT detected, load old values and set program values accordingly.
            // System.out.println("Setting program values from config");

            fieldCheckingURL.setText(s.getConfigURL());
            updateURL();

            fieldTownName.setText(s.getConfigTown());
            updateTown();

            fieldZIPCode.setText(s.getConfigZIP());

            try {
                updatePredictionLabel();
            } catch (NullPointerException ex) {
                // System.out.println("No ZIP code found in config.");
            }
        }

        if (fieldCheckingURL.getText().isEmpty()) {
            fieldTownName.setText("Town");
            fieldTownName.setEnabled(false);
            // System.out.println("Graying out town field");
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        panelStatus = new javax.swing.JPanel();
        lblStatus = new javax.swing.JLabel();
        btnRefresh = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        panelPrediction = new javax.swing.JPanel();
        lblPrediction = new javax.swing.JLabel();
        panelSettings = new javax.swing.JPanel();
        btnSetTown = new javax.swing.JButton();
        fieldTownName = new javax.swing.JTextField();
        fieldCheckingURL = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        fieldZIPCode = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setAutoRequestFocus(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }

            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        lblStatus.setText("Town Not Set");

        btnRefresh.setText("Refresh");
        btnRefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRefreshActionPerformed(evt);
            }
        });

        jLabel2.setText("Status:");

        javax.swing.GroupLayout panelStatusLayout = new javax.swing.GroupLayout(panelStatus);
        panelStatus.setLayout(panelStatusLayout);
        panelStatusLayout.setHorizontalGroup(panelStatusLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelStatusLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(panelStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(btnRefresh, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(panelStatusLayout.createSequentialGroup()
                                        .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 117,
                                                Short.MAX_VALUE)
                                        .addGap(18, 18, 18).addComponent(lblStatus)))
                        .addContainerGap()));
        panelStatusLayout.setVerticalGroup(panelStatusLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(panelStatusLayout.createSequentialGroup().addContainerGap()
                        .addGroup(panelStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(lblStatus).addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 47, Short.MAX_VALUE)
                        .addComponent(btnRefresh).addContainerGap()));

        jTabbedPane1.addTab("Current Status", panelStatus);

        lblPrediction.setText("No ZIP Entered");

        javax.swing.GroupLayout panelPredictionLayout = new javax.swing.GroupLayout(panelPrediction);
        panelPrediction.setLayout(panelPredictionLayout);
        panelPredictionLayout.setHorizontalGroup(
                panelPredictionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(panelPredictionLayout.createSequentialGroup().addContainerGap()
                                .addComponent(lblPrediction).addContainerGap(137, Short.MAX_VALUE)));
        panelPredictionLayout.setVerticalGroup(
                panelPredictionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(panelPredictionLayout.createSequentialGroup().addContainerGap()
                                .addComponent(lblPrediction).addContainerGap(81, Short.MAX_VALUE)));

        jTabbedPane1.addTab("Prediction", panelPrediction);

        btnSetTown.setText("Set Town");
        btnSetTown.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSetTownActionPerformed(evt);
            }
        });

        fieldTownName.setText("Town");
        fieldTownName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fieldTownNameActionPerformed(evt);
            }
        });

        fieldCheckingURL.setToolTipText("");
        fieldCheckingURL.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                fieldCheckingURLFocusLost(evt);
            }
        });
        fieldCheckingURL.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                fieldCheckingURLKeyTyped(evt);
            }
        });

        jLabel1.setText("URL:");
        jLabel1.setToolTipText("The URL of your state's closings list");

        jLabel4.setText("ZIP Code:");

        fieldZIPCode.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                fieldZIPCodeFocusLost(evt);
            }
        });
        fieldZIPCode.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fieldZIPCodeActionPerformed(evt);
            }
        });
        fieldZIPCode.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                fieldZIPCodeKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout panelSettingsLayout = new javax.swing.GroupLayout(panelSettings);
        panelSettings.setLayout(panelSettingsLayout);
        panelSettingsLayout.setHorizontalGroup(panelSettingsLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(panelSettingsLayout.createSequentialGroup().addContainerGap().addGroup(panelSettingsLayout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(panelSettingsLayout.createSequentialGroup().addComponent(fieldTownName)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnSetTown))
                        .addGroup(panelSettingsLayout.createSequentialGroup().addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(fieldCheckingURL))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                panelSettingsLayout.createSequentialGroup().addComponent(jLabel4).addGap(18, 18, 18)
                                        .addComponent(fieldZIPCode, javax.swing.GroupLayout.PREFERRED_SIZE, 134,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap()));
        panelSettingsLayout.setVerticalGroup(panelSettingsLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(panelSettingsLayout.createSequentialGroup().addContainerGap().addGroup(panelSettingsLayout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(btnSetTown)
                        .addComponent(fieldTownName, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(
                                panelSettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(fieldCheckingURL, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(
                                panelSettingsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jLabel4).addComponent(fieldZIPCode,
                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

        jTabbedPane1.addTab("Settings", panelSettings);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING,
                        javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                        layout.createSequentialGroup().addComponent(jTabbedPane1,
                                javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSetTownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSetTownActionPerformed
        updateTown(); //This is what happens when "Set Town" is clicked.
    }//GEN-LAST:event_btnSetTownActionPerformed

    private void updateTown() { //Updates town, starts auto-update thread, and writes new town to config.
        try {
            town = fieldTownName.getText();
            s.setConfigTown(fieldTownName.getText());
            s.writeConfig();
            lblStatus.setText(Checker.check(town, URL));
            Thread t = new Thread(this);
            t.start();
        } catch (IOException ex) {
            Logger.getLogger(SchoolChecker.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void fieldTownNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fieldTownNameActionPerformed
        // TODO Make this update town, update properties file when focus lost
    }//GEN-LAST:event_fieldTownNameActionPerformed

    private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshActionPerformed
        try {
            lblStatus.setText(Checker.check(town, URL));
        } catch (IOException ex) {
            Logger.getLogger(SchoolChecker.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnRefreshActionPerformed

    private void fieldCheckingURLFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_fieldCheckingURLFocusLost
        updateURL();
    }//GEN-LAST:event_fieldCheckingURLFocusLost

    private void updateURL() { //Updates the URL 
        if (fieldCheckingURL.getText().isEmpty()) {
            fieldTownName.setEnabled(false);
        } else {
            fieldTownName.setEnabled(true);
            URL = fieldCheckingURL.getText();
            s.setConfigURL(fieldCheckingURL.getText());
            try {
                Checker.check(town, URL);
                s.writeConfig();
            } catch (IOException ex) {
                System.out.println("Invalid URL entered: " + URL);
            }
        }
    }

    private void fieldCheckingURLKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_fieldCheckingURLKeyTyped
        updateGrayedOut(); //If URL is empty, don't let the user put anything in the town field. Pesky little user. :P
    }//GEN-LAST:event_fieldCheckingURLKeyTyped

    private void updateGrayedOut() {
        if (fieldCheckingURL.getText().isEmpty()) {
            fieldTownName.setEnabled(false);
        } else {
            fieldTownName.setEnabled(true);
        }
    }

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        s.closeStreams();
        // System.out.println("Window Closed"); //Close streams on exit.
    }//GEN-LAST:event_formWindowClosed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        s.closeStreams();
        // System.out.println("Window Closed"); //Close streams on exit.
    }//GEN-LAST:event_formWindowClosing

    private void fieldZIPCodeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fieldZIPCodeActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_fieldZIPCodeActionPerformed

    private void fieldZIPCodeKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_fieldZIPCodeKeyTyped
        //        try {
        //            WxDataGetter.setZIP(Integer.valueOf(fieldZIPCode.getText()));
        //        } catch (JSONException ex) {
        //            Logger.getLogger(SchoolChecker.class.getName()).log(Level.SEVERE, null, ex);
        //        }
    }//GEN-LAST:event_fieldZIPCodeKeyTyped

    private void fieldZIPCodeFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_fieldZIPCodeFocusLost
        try {
            WxDataGetter.setZIP(fieldZIPCode.getText());
        } catch (JSONException | IOException ex) {
            Logger.getLogger(SchoolChecker.class.getName()).log(Level.SEVERE, null, ex);
        }

        s.setConfigZIP(fieldZIPCode.getText());

        updatePredictionLabel();

    }//GEN-LAST:event_fieldZIPCodeFocusLost

    private void updatePredictionLabel() {
        lblPrediction.setText("Temperature: " + String.valueOf(WxDataGetter.getTemp()) + "\nPrecipitation: "
                + String.valueOf(WxDataGetter.getPrecip()));
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        try {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
                        .getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(SchoolChecker.class.getName())
                        .log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(SchoolChecker.class.getName())
                        .log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(SchoolChecker.class.getName())
                        .log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(SchoolChecker.class.getName())
                        .log(java.util.logging.Level.SEVERE, null, ex);
            }

            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

            //</editor-fold>
            try {

                if (UpdateChecker.checkUpdate()) {
                    UpdateChecker.update();
                }

            } catch (IOException ex) {
                Logger.getLogger(SchoolChecker.class.getName()).log(Level.SEVERE, null, ex);
            }

            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new SchoolChecker().setVisible(true);
                }
            });
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(SchoolChecker.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(SchoolChecker.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(SchoolChecker.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(SchoolChecker.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnRefresh;
    private javax.swing.JButton btnSetTown;
    private javax.swing.JTextField fieldCheckingURL;
    private javax.swing.JTextField fieldTownName;
    private javax.swing.JTextField fieldZIPCode;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JLabel lblPrediction;
    private javax.swing.JLabel lblStatus;
    private javax.swing.JPanel panelPrediction;
    private javax.swing.JPanel panelSettings;
    private javax.swing.JPanel panelStatus;
    // End of variables declaration//GEN-END:variables
}