Solved

Display Query Result in JTable using Netbeans

Posted on 2006-07-09
7
21,239 Views
Last Modified: 2008-01-09
Hello everyone,
I am using Netbeans 5.0 and I have successfully connected to and populated a MySQL database.
I am trying to display the results in a JTable.  I have seen many examples of creating only a JTable in a new JFrame but I would like to do more.  I would like to drag and drop a JTable onto a JPanel so I can add more to the panel such as a title and set the background color of the panel.  I would also to alter the color of the table itself.  Netbeans makes this very easy but I am having difficulty displaying the database results.  The following is the code I have so far.  Any help would be greatly appreciated.  Thank you.

* I have tried to place the last two lines of the following program in the
   "Custom Creation Code"  of the JTable in order to pass in the parameters of "data" and
   "columnNames" but this doesn't seem to work either. *

public class DisplaySolarSystemTable extends javax.swing.JFrame
{
    Vector columnNames = new Vector();
    Vector data = new Vector();  
   
    public DisplaySolarSystemTable()
    {
        initComponents();
       
        try
        {          
           //  Connect to the Database
           String driver = "com.mysql.jdbc.Driver";
           String url = "jdbc:mysql://localhost/SolarSystem";
           String userId = "brian";
           String password = "shadowdog";
           Class.forName(driver);
           Connection connection = DriverManager.getConnection(url, userId, password);
           

           //  Read data from a table
           String sql = "SELECT * FROM solarsystemtable";
           Statement stmt = connection.createStatement();
           ResultSet rs = stmt.executeQuery( sql );
           ResultSetMetaData md = rs.getMetaData();
           int columns = md.getColumnCount();
           
           //  Get column names
           for (int i = 1; i <= columns; i++)
           {
              columnNames.addElement( md.getColumnName(i) );
           }
           
           //  Get row data
           while (rs.next())
           {
              Vector row = new Vector(columns);
              for (int i = 1; i <= columns; i++)
              {
                 row.addElement(rs.getObject(i));
              }
              data.addElement(row);
           }
           rs.close();
           stmt.close();
        }
        catch(ClassNotFoundException cnfe)
        {
           cnfe.printStackTrace();
        }
        catch(SQLException sqle) {
          sqle.printStackTrace();  
        }

       JTable table = new JTable(data, columnNames);
       JScrollPane scrollPane = new JScrollPane( table );
}
0
Comment
Question by:brian_huelsman
  • 3
  • 2
7 Comments
 
LVL 35

Expert Comment

by:girionis
ID: 17070975
Hi brian_huelsman

you need to add your table to a panel and the panel to your jframe. Then you should make your jframe visible. Try the following

table.setPreferredScrollableViewportSize(new Dimension(500, 70));
JScrollPane scrollPane = new JScrollPane( table );
JPanel panel = new JPanel();
panel.add(scrollPane);
this.setContentPane(panel);
this.pack();
this.setVisible(true);

Cheers
0
 
LVL 35

Expert Comment

by:girionis
ID: 17070992
typo

> add your table t

to add your jscrollpane
0
 

Author Comment

by:brian_huelsman
ID: 17074303
Thank you for your answer girionis.  However, I forgot to mention that I already have created the above in the gui editor.  When I click on the design window I already have a JFrame, a JPanel, and a JTable already in place.  Additionally, The JTable is an instance of a JScrollPane.  Here is the complete code minus the last two lines from the previous post that should not be needed here because they are generated automatically when a component is created.  Is there something that I can to the main code page or do I need to add code to the JTable's properties via "Custom Creation Code" , "Post Creation Code"... to get the query results to display?
Thank you again.


package AfterDarkJournal;

import java.io.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;  
import javax.swing.JFrame.*;
import java.awt.*;

public class DisplaySolarSystemTable extends javax.swing.JFrame
{
    Vector columnNames = new Vector();
    Vector data = new Vector();  
   
    public DisplaySolarSystemTable()
    {
        initComponents();
       
        try
        {          
           //  Connect to the Database
           String driver = "com.mysql.jdbc.Driver";
           String url = "jdbc:mysql://localhost/SolarSystem";
           String userId = "brian";
           String password = "shadowdog";
           Class.forName(driver);
           Connection connection = DriverManager.getConnection(url, userId, password);
           

           //  Read data from a table
           String sql = "SELECT * FROM solarsystemtable";
           Statement stmt = connection.createStatement();
           ResultSet rs = stmt.executeQuery( sql );
           ResultSetMetaData md = rs.getMetaData();
           int columns = md.getColumnCount();
           
           //  Get column names
           for (int i = 1; i <= columns; i++)
           {
              columnNames.addElement( md.getColumnName(i) );
           }
           
           //  Get row data
           while (rs.next())
           {
              Vector row = new Vector(columns);
              for (int i = 1; i <= columns; i++)
              {
                 row.addElement(rs.getObject(i));
              }
              data.addElement(row);
           }
           rs.close();
           stmt.close();
        }
        catch(ClassNotFoundException cnfe)
        {
           cnfe.printStackTrace();
        }
        catch(SQLException sqle) {
          sqle.printStackTrace();  
        }
    }
   
    --------------------------------- Lines Generated Automatically -----------------------------------

    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jPanel1.setBackground(new java.awt.Color(0, 0, 0));
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null}
            },
            new String [] {
                "Object Type", "Object Name", "Photo", "Diameter Size in Miles", "Distance from Sun in Miles", "Number of Satellites", "Apparent Magnitude"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 930, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(108, 108, 108)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 363, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(218, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        pack();
    }// </editor-fold>

-----------------------------------------------------------------------------------------------------------
   

    public static void main(String args[])
    {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                new DisplaySolarSystemTable().setVisible(true);
            }
        });
    }
   
    // Variables declaration - do not modify
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration

}
0
 

Author Comment

by:brian_huelsman
ID: 17077102
I just wanted to add that I can see the JTable but the results are not being displayed
inside the cells.  I have tried the above and it works when it creates the table "on the fly" so to speak, but not when I create the table and place it in a frame that I have designed via the gui editor.  Futhermore, I have tried something like:
 jTable1 = new javax.swing.JTable(data, columnNames); by altering the "Custom Creation Code"
property of the table but the results still do not show up.  I hoped that just as in the original code that works that if I passed in these two parameters into the table inself that it would show the query results, but it does not.

Brian Huelsman
0
 
LVL 35

Accepted Solution

by:
girionis earned 500 total points
ID: 17079211
Ok I see... I thought you were not able to see any of the GUI. What you can do to update the table is to get the model of the table and add a row there. SOmething like the following code:


DefaultTableModel model = (DefaultTableModel) jTable1.getModel();

//  Get row data
           while (rs.next())
           {
              Vector row = new Vector(columns);
              for (int i = 1; i <= columns; i++)
              {
                    row.addElement(rs.getObject(i));
                    model.addRow(row);         // This should add the row to the table
              }
              data.addElement(row);
           }
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
array11 challenge 16 51
pairstar challenge 2 41
json format text only 4 65
Java asynchronous logging 4 34
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now