Hi,

Could anyone help me with this problem, the following code contains the GUI for a chargeback application which was handed on to me. I want to be able to test the components DC1 and DC2 to make sure information was entered when the btnGenChargeReport button is clicked...
:?:
I used an if/else statement within the try statement before the writeable workbook statement, but nothing happens...

package chargereport;


import java.awt.event.ActionEvent;
import java.io.*;
import javax.swing.*;
import java.sql.*;
import java.util.*;
import java.io.File; 
import jxl.*; 
import jxl.write.*; 
import com.toedter.calendar.JDateChooser;
import java.text.SimpleDateFormat;


public class CRTest extends javax.swing.JFrame
{

    String username;
    String password;
    private com.toedter.calendar.JDateChooser txtDC1;
    private com.toedter.calendar.JDateChooser txtDC2;
    javax.swing.JButton btnClose = new javax.swing.JButton();


    public void setUsername(String newValue) 
    {
        username = newValue;
    }   

    public void setPassword(String newValue) 
    {
        password = newValue;
    }  


    /** Creates new form ChargeReport */
    public CRTest()
    {
        initComponents();

    }

    /** 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.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                          
    private void initComponents() 
    {
        javax.swing.JButton btnGenChargeReport;

        javax.swing.JLabel jLabel1;
        javax.swing.JLabel jLabel2;
        javax.swing.JLabel jLabel3;
        javax.swing.JLabel jLabel4;
        /*javax.swing.JTextField tfEndDate;
        javax.swing.JTextField tfStartDate;*/

        btnGenChargeReport = new javax.swing.JButton();

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtDC1=new JDateChooser("yyyy-MM-dd","##-##-####",'_');
        txtDC2=new JDateChooser("yyyy-MM-dd","##-##-####",'_');


        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Generate Charge Report");

        btnClose.setText("Close");


        btnGenChargeReport.setText("Generate Charge Report");
        btnGenChargeReport.addActionListener(new java.awt.event.ActionListener() {            
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGenChargeReportActionPerformed(evt);
            }
        });

        btnClose.addActionListener(new java.awt.event.ActionListener() {            
            public void actionPerformed(java.awt.event.ActionEvent e) {
                btnCloseActionPerformed(e);
            }

        });


        jLabel1.setText("Start Date");

        jLabel2.setText("End Date");

        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText("[yyyy-mm-dd]");

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel4.setForeground(new java.awt.Color(255, 0, 51));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)

                    .addGroup(layout.createSequentialGroup()                  
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)                         
                            .addComponent(txtDC1,javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))

                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 61, Short.MAX_VALUE)

                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtDC2,javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))

                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
                             )


                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                          //---------------------------
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()                     
                            .addComponent(btnGenChargeReport, javax.swing.GroupLayout.DEFAULT_SIZE, 77, javax.swing.GroupLayout.DEFAULT_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
                            .addComponent(btnClose, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                             ))
                         )
                     ) );

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)

                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))

                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(txtDC1)
                    .addComponent(txtDC2))

                .addGap(4, 4, 4)
                    .addComponent(jLabel3)
                .addGap(22, 22, 22) 

                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(btnGenChargeReport)
                    .addComponent(btnClose))

                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                /*.addComponent(txtDC)*/
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

        private void btnCloseActionPerformed(ActionEvent e) 
            {               
                if(e.getSource() == btnClose)
            {
                System.exit(0);
            }
            else
            {
                JOptionPane.showMessageDialog(null, "Try the big red X to close the window.", "Problems Exiting?", JOptionPane.WARNING_MESSAGE);
            }
            }



    private void btnGenChargeReportActionPerformed(java.awt.event.ActionEvent evt)                                                   
    {                                                       
// TODO add your handling code here:  

        try 
        {

        SimpleDateFormat format1=new SimpleDateFormat(this.txtDC1.getDateFormatString());
        String DC1=format1.format(this.txtDC1.getDate());
        System.out.println(DC1);
        SimpleDateFormat format2=new SimpleDateFormat(this.txtDC2.getDateFormatString());
        String DC2=format2.format(this.txtDC2.getDate());
        System.out.println(DC2);//the above 6 lines formats the date to a string in the form yyyy-mm-dd

        WritableWorkbook workbook = Workbook.createWorkbook(new File("ChargeReportTrial.xls"));
        WritableSheet sheet = workbook.createSheet("Charge Report", 0);

        sheet.setColumnView(0,45);
        sheet.setColumnView(1,20);
        sheet.setColumnView(2,25);
        sheet.setColumnView(3,20);

        Label lblEmpName = new Label(0, 0, "EMPLOYEE'S NAME");
        Label lblRegNum = new Label(1,0,"BADGE NUMBER") ;
        Label lblStatus = new Label(2,0, "STATUS");
        Label lblAmt = new Label(3,0,"AMOUNT");

        sheet.addCell(lblEmpName);
        sheet.addCell(lblRegNum);
        sheet.addCell(lblStatus);
        sheet.addCell(lblAmt);

        Connection cn = DriverManager.getConnection("jdbc:mysql://paptais02/OperatorCalls" , username,password);
        Statement stmt = cn.createStatement();

        String query = "select CONCAT(FirstName, ' ', LastName), cl.EmployeeID, SUM(tollcharge) ";
        query = query + "from Call_Log as cl, emp as c, tsttbills as b ";
        query = query + "where cl.EmployeeID = c.EmployeeID and cl.NumberCalled = b.callednumber and cl.CallDate = b.date ";
        query = query + "and b.date >= ";
        query = query + DC1;
        query = query + " and b.date <= ";
        query = query + DC2;
        query = query + " group by CONCAT(FirstName,' ', LastName), EmployeeID;";

        System.out.println(query);

        ResultSet rs = stmt.executeQuery(query);
        int r = 1;

        while (rs.next()) 
        {
            Label EmpNameValue = new Label(0,r, rs.getString(1));
            Label RegNumValue = new Label(1,r , rs.getString(2));
            Label StatusValue = new Label(2,r , rs.getString(3));
            Label AmtValue = new Label(3,r , rs.getString(4));

            sheet.addCell(EmpNameValue);
            sheet.addCell(RegNumValue);
            sheet.addCell(StatusValue);
            sheet.addCell(AmtValue);

            r = r + 1;
        }        

        workbook.write();
        workbook.close(); 
        }

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

        }

   // }


     public static void main(String args[])
    {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new CRTest().setVisible(true);
            }
        });
    }
}

Dani AI

Generated

As guessed, the JDateChooser component will return null if the user has not picked a date — calling format.format(txtDC1.getDate()) when getDate() is null throws a NullPointerException, which in your code ends up in the catch with only a stack trace and no user feedback. (ssec.wisc.edu)

Practical fixes (apply before creating the workbook or running the query):

  • Validate the picks up front and give a clear message to the user (avoid relying on exceptions for flow control).
  • Ensure the start date is not after the end date.
  • Convert the chosen java.util.Date to a JDBC java.sql.Date (or to LocalDate) and use parameterized SQL (PreparedStatement) instead of concatenating strings.

Example validation snippet to run first:

Date start = txtDC1.getDate();
Date end = txtDC2.getDate();
if (start == null || end == null) {
    JOptionPane.showMessageDialog(this, "Please select both start and end dates.");
    return;
}
if (start.after(end)) {
    JOptionPane.showMessageDialog(this, "Start date must be before or equal to end date.");
    return;
}

Avoid building the WHERE clause by concatenating date strings. Use a PreparedStatement and set java.sql.Date parameters so the driver sends proper DATE literals and you avoid SQL injection and quoting problems. Example pattern:

String sql = "SELECT CONCAT(FirstName,' ',LastName) AS name, cl.EmployeeID, SUM(tollcharge) AS amount "
           + "FROM Call_Log cl JOIN emp c ON cl.EmployeeID=c.EmployeeID "
           + "JOIN tsttbills b ON cl.NumberCalled=b.callednumber AND cl.CallDate=b.date "
           + "WHERE b.date>=? AND b.date<=? GROUP BY name, EmployeeID";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDate(1, new java.sql.Date(start.getTime()));
ps.setDate(2, new java.sql.Date(end.getTime()));

PreparedStatement#setDate and the java.sql.Date conversion are the standard approach. (docs.oracle.com)

Also fix the result-set mapping: your SELECT returns three columns (name, EmployeeID, SUM), but the original code attempts to read four columns — that mismatch will throw an exception. Rename/alias columns (as above) and read them in the same order you selected them.

Note: moved this project to PHP later, but the pattern above will help anyone keeping it in Java and makes the UI validation, SQL, and Excel writing much more robust.

Recommended Answers

All 2 Replies

It's somewhat dependent upon what "com.toedter.calendar.JDateChooser" returns when you call getDate() if nothing has been chosen. Does it return a null? A default date? If you were just checking for a valid date from a string you'd just catch the exception thrown by SimpleDateFormat.parse(). Since you're using some custom component to return the date though, you'll have to figure out what it's returning for no selection.

Hi Ezzarel,

I changed this part of the project from Java to PHP (which is a lot more convenient).
Thanks alot for the help though...
:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.