user4188835
user4188835

Reputation:

Outputting database data to a JTable

I've been trying to follow the information here and and the code here and I'm having some difficulty.

The database query works and I've outputted it successfully to console. Following the above guides I've since added some code that puts the ResultSet data into the required Vectors. This is my code:

public class Reports extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JPanel contentPane;
    private JTextField dateFromYYYY;
    private JTextField dateFromMM;
    private JTextField dateFromDD;
    private JTextField dateToYYYY;
    private JTextField dateToMM;
    private JTextField dateToDD;

    private JTextField ownerNameInput;
    private JTextField petNameInput;
    private JTextField doctorNameInput;

    private JCheckBox isPaid = new JCheckBox("Is Paid");

    public static JTable table;
    public static boolean printTable = true;
    private String printHeader;

    // Static Variables

    private final static String BOOKINGS_TABLES = "FROM Doctor, Pet, Treatment, Visit ";

    /**
     * Create the frame.
     */
    private void SearchFrame() {
        setTitle("Generate a Report");
        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        setBounds(100, 100, 981, 551);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel lblWhatWouldYou = new JLabel("What would you like a report for?");
        lblWhatWouldYou.setBounds(36, 10, 200, 50);
        contentPane.add(lblWhatWouldYou);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(260, 60, 690, 370);
        contentPane.add(scrollPane);

        table = new JTable();
        scrollPane.setViewportView(table);
    }


    private void DateFields(){
        // From Date
        //Year
        JLabel lblFromDate = new JLabel("From          dd:");
        lblFromDate.setBounds(20, 180, 165, 25);
        contentPane.add(lblFromDate);

        JLabel lblFromYear = new JLabel("yyyy:");
        lblFromYear.setBounds(180, 180, 165, 25);
        contentPane.add(lblFromYear);
        dateFromYYYY = new JTextField();
        dateFromYYYY.setBounds(210, 180, 40, 25);
        contentPane.add(dateFromYYYY);

        //Month
        JLabel lblFromMonth = new JLabel("mm:");
        lblFromMonth.setBounds(128, 180, 165, 25);
        contentPane.add(lblFromMonth);
        dateFromMM = new JTextField();
        dateFromMM.setBounds(155, 180, 20, 25);
        contentPane.add(dateFromMM);

        dateFromDD = new JTextField();
        dateFromDD.setBounds(100, 180, 20, 25);
        contentPane.add(dateFromDD);

        // To Date
        //Year
        JLabel lblToDate = new JLabel("To               dd:");
        lblToDate.setBounds(20, 210, 165, 25);
        contentPane.add(lblToDate);

        JLabel lblToYear = new JLabel("yyyy:");
        lblToYear.setBounds(180, 210, 165, 25);
        contentPane.add(lblToYear);
        dateToYYYY = new JTextField();
        dateToYYYY.setBounds(210, 210, 40, 25);
        contentPane.add(dateToYYYY);

        //Month
        JLabel lblToMonth = new JLabel("mm:");
        lblToMonth.setBounds(128, 210, 165, 25);
        contentPane.add(lblToMonth);
        dateToMM = new JTextField();
        dateToMM.setBounds(155, 210, 20, 25);
        contentPane.add(dateToMM);

        dateToDD = new JTextField();
        dateToDD.setBounds(100, 210, 20, 25);
        contentPane.add(dateToDD);

    }

    private void PetName(){
        JLabel lblPetName = new JLabel("Pet Name:");
        lblPetName.setBounds(20, 90, 165, 25);
        contentPane.add(lblPetName);

        petNameInput = new JTextField();
        petNameInput.setBounds(100, 90, 150, 25);
        contentPane.add(petNameInput);
    }

    private void OwnerName(){
        JLabel lblOwnerName = new JLabel("Owner Name:");
        lblOwnerName.setBounds(20, 120, 165, 25);
        contentPane.add(lblOwnerName);

        ownerNameInput = new JTextField();
        ownerNameInput.setBounds(100, 120, 150, 25);
        contentPane.add(ownerNameInput);
    }

    private void DoctorName(){
        JLabel lblDoctorName = new JLabel("Doctor Name:");
        lblDoctorName.setBounds(20, 150, 165, 25);
        contentPane.add(lblDoctorName);

        doctorNameInput = new JTextField();
        doctorNameInput.setBounds(100, 150, 150, 25);
        contentPane.add(doctorNameInput);
    }

    private void IsPaidCheckBox(){
        isPaid.setBounds(155, 250, 97, 25);
        contentPane.add(isPaid);
    }

    public void Bookings() {
        // Local variables
        Vector<Object> columnNames = new Vector<Object>();
        Vector<Object> data = new Vector<Object>();

        // Instantiate the frame
        SearchFrame();
        // Set search fields
        PetName();
        OwnerName();
        DoctorName();
        IsPaidCheckBox();
        DateFields();

        JButton btnSearch = new JButton("Search");
        btnSearch.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String queryString00 = "";
                String queryString01 = "SELECT pet.petname AS [Pet Name], pet.ownerName AS [Owner Name], doctor.doctorName AS [Doctor Name], visit.visitDate AS [Visit Date], treatment.treatmentName AS [Treatment Name], visit.ispaid AS [Is Paid] ";
                String queryString03 = "WHERE Visit.petID = Pet.petID ";
                String queryString02 = " GROUP BY visitID;";

                // build the query
                if(!(petNameInput.getText().equals("")))
                    queryString00 =  queryString01 + BOOKINGS_TABLES + queryString03 + "AND petname LIKE " + "'%" + petNameInput.getText() + "%'";
                else queryString00 =  queryString01 + BOOKINGS_TABLES + queryString03;

                if(!(ownerNameInput.getText().equals("")))
                    queryString00 = queryString00 + "AND ownername LIKE " + "'%" + ownerNameInput.getText() + "%'";

                if(!(doctorNameInput.getText().equals("")))
                    queryString00 = queryString00 + "AND doctorname LIKE " + "'%" + doctorNameInput.getText() + "%'";


                if(!(dateFromYYYY.getText().equals(""))){
                    String fromString = dateFromYYYY.getText() + "-" + dateFromMM.getText() + "-" + dateFromDD.getText();
                    queryString00 = queryString00 + " AND visitdate >= '" + fromString + "'";
                }

                if(!(dateToYYYY.getText().equals(""))){
                    String toString = dateToYYYY.getText() + "-" + dateToMM.getText() + "-" + dateToDD.getText();
                    queryString00 = queryString00 + " AND visitdate <= '" + toString + "'";
                }

                if(isPaid.isSelected())
                    queryString00 = queryString00 + " AND ispaid = 'Y'";

                queryString00 = queryString00 + queryString02;
//              System.out.println(queryString00);

                DatabaseConnection db = new DatabaseConnection();
                db.openConn();

                // Get query
                ResultSet rs = db.getSearch(queryString00);
                ResultSetMetaData md = null;

                // Set up vectors for table output
                // Output query to screen (Much of the following code is adapted from http://www.camick.com/java/source/TableFromDatabase.java)
                try{
                    md = rs.getMetaData();
                    int columnCount = md.getColumnCount();
                    // Get column names
                    for(int i = 1; i <= columnCount; i++)
                        columnNames.addElement(md.getColumnName(i));

                    while(rs.next()){
//                      System.out.printf("%-15s%-15s%-15s%-15s%-15s%-15s\n", rs.getString("Pet Name"), rs.getString("Owner Name"), rs.getString("Doctor Name"), rs.getString("Visit Date"), rs.getString("Treatment Name"), rs.getString("Is Paid"));
                        Vector<Object> row = new Vector<Object>(columnCount);
                        for(int i = 1; i <= columnCount; i++)
                            row.addElement(rs.getObject(i));
                        data.addElement(row);
                    }
                }
                catch (SQLException e) {
                    e.printStackTrace();
                }
                db.closeConn();
                }

        //  Create table with database data
            DefaultTableModel model = new DefaultTableModel(data, columnNames)
            {
                /**
                 * 
                 */
                private static final long serialVersionUID = 1L;

                @SuppressWarnings("unchecked")
                @Override
                public Class getColumnClass(int column)
                {
                    for (int row = 0; row < getRowCount(); row++)
                    {
                        Object o = getValueAt(row, column);

                        if (o != null)
                        {
                            return o.getClass();
                        }
                    }

                    return Object.class;
                }
            };

            // Out put to the table (theoretically)
            JTable table = new JTable(columnNames, data);
            this.scrollPane.setViewportView(table);
//          JScrollPane scrollPane = new JScrollPane( table );
//          getContentPane().add( scrollPane );

        });
        btnSearch.setBounds(36, 460, 165, 25);
        contentPane.add(btnSearch);

        JLabel resultLabel = new JLabel("Reports will be printed below");
        resultLabel.setBounds(515, 10, 312, 50);
        contentPane.add(resultLabel);

        JButton printReport = new JButton("Print Report");
        printReport.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {
                    String resultLabelPrint = resultLabel.getText();
                    MessageFormat footer = new MessageFormat(resultLabelPrint);
                    MessageFormat header = new MessageFormat(printHeader);
                    boolean complete =table.print(JTable.PrintMode.FIT_WIDTH, header , footer );
                    if (complete) {
                        /* show a success message  */

                    } else {
                        /*show a message indicating that printing was cancelled */

                    }
                } catch (PrinterException pe) {
                    /* Printing failed, report to the user */

                }
            }
        });
        printReport.setBounds(473, 460, 227, 25);
        contentPane.add(printReport);

    }

}

The final part of the code, which I believe out puts to the table, gives me some weird errors.

            // Out put to the table (theoretically)
            JTable table = new JTable(columnNames, data);
            this.scrollPane.setViewportView(table);
//          JScrollPane scrollPane = new JScrollPane( table );
//          getContentPane().add( scrollPane );

The first line gives me a syntax error on the semi-colon (;), specifically, Syntax error on token ";", invalid AssignmentOperator. I get the same when I try the 'model' variable.

When I uncomment the last two lines I get 'Syntax error on token ".", { expected' and the Eclipse demands another closing { despite there not being a corresponding opening }. If I add it then I get more errors.

I suspect this has something to do with the class structure of the code that I'm trying to follow but I'm having no luck in following those either.

All I want to do is to take the information that I have and output it in the table which is already there. How do I do this?

Upvotes: 1

Views: 166

Answers (2)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48723

scrollPane is not a global instance.

Move JScrollPane scrollPane out of your method SearchFrame() and place it into your list of instance variables for the class.

That is only your immediate and first issue, your other issue is that your are attempting to access instance variables defined in Reports within the scope of 2x nested anonymous classes.

You should parametarize your GUI methods to accept the components for injection into the panels.

public class Reports extends JFrame {
    JScrollPane scrollPane;
    ...

    private void SearchFrame() {
        scrollPane = new JScrollPane ();
    }
    ...

    public void Bookings() {
        scrollPane...
        ...
    }
    ...
}

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

You're not showing all the error messages nor the complete error messages (please fix this). The most important one is the, Cannot refer to the non-final local variable data defined in an enclosing scope message. So make the variables final -- one problem solved.

public void Bookings() {
    // Local variables
    final Vector<Object> columnNames = new Vector<Object>(); //!! made final
    final Vector<Object> data = new Vector<Object>();

The other problem is that this code:

       JTable table = new JTable(columnNames, data);
       this.scrollPane.setViewportView(table);

Is being called outside of any and all methods. You need to match up your curly braces carefully.

Question that confuses me about your code though -- why create a TableModel and not use it as a model for your JTable?

Upvotes: 2

Related Questions