Java Video Tutorial 36

Java JTable TutorialI’ve been asked to make a Java JTable tutorial by many people. Today I’ll show you how to display database query results from my Sabermetrics Tutorial into a Java JTable.

I then cover most everything about Java JTables. How to display data into a JTable. How to change fonts in a JTable. How to change row height in a JTable. How to sort a JTable. How to align a JTable column and much more.

All of the code follows the tutorial and it has even more tricks.

If you like videos like this, please tell Google

Code from the Video

import java.awt.BorderLayout;
import java.awt.Font;
import java.sql.*;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

public class Lesson36{
	// Used to hold the column data for each player
	static Object[][] databaseInfo;
	// The column titles for the JTable
    static Object[] columns = {"Year", "PlayerID", "Name", "TTRC", "Team", "Salary", "CPR", "POS"};
    // A ResultSet contains a table of data filled 
    // with the results of the query.
    static ResultSet rows;
    // ResultSetMetaData contains information on
    // the data returned by the query
    static ResultSetMetaData metaData;
    // DefaultTableModel defines the methods JTable will use
    // I'm overriding the getColumnClass
    static DefaultTableModel dTableModel = new DefaultTableModel(databaseInfo, columns){
        public Class getColumnClass(int column) {
            Class returnValue;
            // Verifying that the column exists (index > 0 && index < number of columns
            if ((column >= 0) && (column < getColumnCount())) {
              returnValue = getValueAt(0, column).getClass();
            } else {
              // Returns the class for the item in the column	
              returnValue = Object.class;
            return returnValue;
	public static void main(String[] args){
		JFrame frame = new JFrame();

	    Connection conn = null;
        try {
            // The driver allows you to query the database with Java
        	// forName dynamically loads the class for you
            // DriverManager is used to handle a set of JDBC drivers
            // getConnection establishes a connection to the database
            // You must also pass the userid and password for the database
            conn = DriverManager.getConnection("jdbc:mysql://localhost/lahman591","mysqladm","turtledove");
            // Statement objects executes a SQL query
            // createStatement returns a Statement object
            Statement sqlState = conn.createStatement();
            // This is the query I'm sending to the database
            String selectStuff = "select b.yearID, b.playerID, " +
            		"CONCAT(m.nameFirst, ' ', m.nameLast) AS Name, " + 
            		"((b.H+b.BB)+(2.4*(b.AB+b.BB)))*(t.TB+(3*(b.AB+b.BB)))/(9*(b.AB+b.BB))-(.9*(b.AB+b.BB)) AS TTRC, " +
            		"b.teamID AS Team, s.salary AS Salary, " +
            		"CAST( s.salary/(((b.H+b.BB)+(2.4*(b.AB+b.BB)))*(t.TB+(3*(b.AB+b.BB)))/(9*(b.AB+b.BB))-(.9*(b.AB+b.BB))) as decimal(10,2)) AS CPR, " +
            		"f.POS AS POS FROM Batting b, Master m, Salaries s, TOTBYR t, Fielding f " +
            		"WHERE b.playerID = m.playerID AND t.playerID = m.playerID " +
            		"AND t.yearID = 2010 AND b.yearID = t.yearID AND s.playerID = b.playerID " + 
            		"AND s.yearID = b.yearID AND b.AB > 50 AND b.playerID = f.playerID " +
            		"AND b.playerID = t.playerID GROUP BY b.playerID ORDER BY TTRC DESC LIMIT 200;";
            /* Have to cut out salary because it isn't in database for 2011 
            String selectStuff = "select b.yearID, b.playerID, " +
            		"CONCAT(m.nameFirst, ' ', m.nameLast) AS NAME, " + 
            		"((b.H+b.BB)+(2.4*(b.AB+b.BB)))*(t.TB+(3*(b.AB+b.BB)))/(9*(b.AB+b.BB))-(.9*(b.AB+b.BB)) AS TTRC, " +
            		"b.teamID AS Team, 0 AS Salary, " +
            		"0 AS CPR, f.POS AS POS " +
            		"FROM Batting b, Master m, Fielding f, TOTBYR as t " +
            		"WHERE b.playerID = m.playerID AND t.playerID = m.playerID " +
            		"AND t.yearID = 2011 AND b.yearID = t.yearID " + 
            		"AND b.AB > 100 AND f.playerID = b.playerID " +
            		"GROUP BY b.playerID ORDER BY TTRC DESC LIMIT 200;";
            // A ResultSet contains a table of data representing the
            // results of the query. It can not be changed and can 
            // only be read in one direction
            rows = sqlState.executeQuery(selectStuff);
            int numOfCol;
            // Retrieves the number, types and properties of the Query Results
            metaData = rows.getMetaData();
            // Returns the number of columns
            numOfCol = metaData.getColumnCount();
            // One way to get the column titles
            columns = new String[numOfCol];
            for(int i=1; i<=numOfCol; i++)
            	// Returns the column name
            	columns[i] = metaData.getColumnName(i);
            // Temporarily holds the row results
            Object[] tempRow;
         // next is used to iterate through the results of a query
            	// Gets the column values based on class type expected
            	tempRow = new Object[]{rows.getInt(1), rows.getString(2), rows.getString(3),
            		rows.getDouble(4), rows.getString(5), rows.getInt(6), rows.getDouble(7),
            	// Adds the row of data to the end of the model
        catch (SQLException ex) {
        	// String describing the error
            System.out.println("SQLException: " + ex.getMessage());
            // Vendor specific error code
            System.out.println("VendorError: " + ex.getErrorCode());
        catch (ClassNotFoundException e) {
			// Executes if the driver can't be found
        // Create a JTable using the custom DefaultTableModel
        JTable table = new JTable(dTableModel);
        // Increase the font size for the cells in the table
        table.setFont(new Font("Serif", Font.PLAIN, 20));
        // Increase the size of the cells to allow for bigger fonts
	    // Allows the user to sort the data

        /* If you want to right justify column
	    TableColumn tc = table.getColumn("TTRC");
	    RightTableCellRenderer rightRenderer = new RightTableCellRenderer();
	    // Disable auto resizing

	    // Set the width for the columns
	    TableColumn col1 = table.getColumnModel().getColumn(0);
	    TableColumn col2 = table.getColumnModel().getColumn(1);
	    TableColumn col3 = table.getColumnModel().getColumn(2);
	    TableColumn col5 = table.getColumnModel().getColumn(5);
	    TableColumn col6 = table.getColumnModel().getColumn(6);
	    // Change justification of column to Center
	    TableColumn tc = table.getColumn("Team");
	    CenterTableCellRenderer centerRenderer = new CenterTableCellRenderer();
	    tc = table.getColumn("POS");
	    centerRenderer = new CenterTableCellRenderer();
	    JScrollPane scrollPane = new JScrollPane(table);
	    frame.add(scrollPane, BorderLayout.CENTER);
	    frame.setSize(800, 500);

// How to change justification to the right

class RightTableCellRenderer extends DefaultTableCellRenderer {   
	  public RightTableCellRenderer() {  

// Change justification to the center

class CenterTableCellRenderer extends DefaultTableCellRenderer {   
	  public CenterTableCellRenderer() {  

46 Responses to “Java Video Tutorial 36”

  1. mr.roshik says:

    Thanks again, we were waiting for this one, and after 5 days we have got this nice tutorial. Wish u have a nice day.

    • admin says:

      I’m glad you like it. I thought it would be fun to actually make a nice tool instead of just covering the API. I have a much bigger project planned. This tutorial series seems to be losing interest so I’m going to experiment with more tutorials like this one.

      I kind of like it when a tutorial loses its audience. Can you tell that I don’t make tutorials just to make money 🙂

  2. Sivada says:

    I never comment on tutorials but I had to comment on yours. THIS WAS A FANTASTIC TUTORIAL ON JTABLE!!!!! It answered most of my questions and I am truly greatful.

    • admin says:

      I’m very happy that I was able to explain this often confusing subject. I just made another video on Java JTables. It and part 38 will cover everything you can do with them. Thank you for taking the time to show your appreciation 🙂

  3. Saleh says:

    I never expected there is something like your tutorials on the internet.

    …..THANK YOU

  4. Danijel Vrgoc says:

    Why is there a table named “TOTBYR” on line 87 when there is no such table given in this database? Error that shows up on my console says: “Table ‘lahman591.totbyr’ doesn’t exist”.”

    I downloaded the this sql database.

    Any idea how to fix this? :-/

  5. Neo says:

    Dear Derek,
    thanks for your awesome tutorials on JTable and SQL, I am a student who is trying to practise some SQL and java coding skills during the winter holiday, your tutorials have been extremely helpful. as you said in this video, this one is a good example for model view controler design. if you are making any totorials about MVC, I was wondering if you could use this JTable and SQL to illustrate MVC, please? (I asked you about MVC tutorial a few days ago) many thanks

  6. Hamraz says:

    SIR kindly teach me how to make a download manager in java and how RMI works
    plz sir………..

  7. fred says:

    This tutorials are THE BEST OF THE BEST – THANKS A LOT !!!

  8. fred says:

    This tutorials are THE BEST OF THE BEST -THANKS A LOT !!!

    Please, add the MVC version of this code in your MVC tutorial

  9. Anonymous says:

    I have seen so many tutorial’s but urs is to the point i realy appreciate for your time hope you will have some new ones for other languages.

  10. James says:

    I have been looking at tutorials on different ways to process ResultSets into JTables for about the past 168 hours straight! I either just couldn’t understand or couldn’t get the other methods to work at all… 🙁
    I found your tutorial today and within an hour I have a working program that processes my ResultSet into a JTable. You are awesome bro! Thank you for taking the time and effort to help people like me.

    – James

    p.s. Before I even saw your post about the e-cig I had been trying to quit smoking for about a week… I still smoke 3 or 4 real ones per day, but it is way better than my usual pack a day! So glad it worked for you, just don’t start again… Who will write these wonderful tuts if you aren’t here for us?

    • Derek Banas says:

      I’m very happy that I was able to help.

      Yes I had quit smoking for a few weeks now and then over the years, but I could never eliminate them 100%. I quit a few months ago so I won’t go back. I’m pretty good at hypnosis, so with a bit of that and the E Cigs I’m good to go now. Keep at it and try a bunch of different devices. I’m still messing around with devices now, but the eGo Twist is pretty great

      • Mateusz says:

        What do you hypnotize us to do?
        Because it is quite unbeliveable
        you create those quality tutorials
        just for fun.
        Just kidding of course. (Or am I?)

        Anyway, many thanks from Poland.
        (yes, we DO have computers here)

        • Derek Banas says:

          That’s funny 🙂 I receive an infinite amount of pleasure from helping so many people! I also get to talk to a ton of extremely nice people all over the world like yourself. Being pretty much a country boy, you can’t imagine how amazing that is to me.

          Thank you for visiting my site

  11. Rasme says:

    ” Unknown column ‘t.playerID’ in ‘where clause’ ” thats what I get when I run the program….I copied your sql code I didnt add and remove anything from it

  12. Rasme says:

    Nice tutorial but I get problem. ” Unknown column ‘t.playerID’ in ‘where clause’ ” thats what I get when I run the program….I copied your sql code I didnt add and remove anything from it

  13. Michael says:

    This makes creating JTables easy. I have been looking for something. Most of the tutorials I found make JTable sound and feel more complicated. Many thanks.

  14. Ron says:


    This is great. Thank you.

  15. Jan says:

    Hi Derek,

    thank you very much for these works. It’s Perfekt.
    Can you help me please? I get error while reading from database. Error is “SQLException: Table ‘lahman.Batting’ doesn’t exist
    VendorError: 1146”

    But i have the table. Do you know why is this Error? GUI is there without any results 🙁

    Thank you.

  16. Sham says:

    Hello Derek,
    Your teaching style is not making me gaining programming sense.
    For example: For displaying data in JTable from Database, you involved many new concepts in this tutorial like overriding methods of parent class, Using syntax like ‘Object.class’, using keyword like ‘Class’.
    So, Looks like i am feeling difficult to grab the purpose of such 3 concepts(above), as you are directly using it in this context.
    It took me one day to understand after runtime debug to know, what is ‘Object.class’, because google also doesn’t show this.

    • Derek Banas says:


      I basically require people to watch every video in order like you would in a college course. That is why I don’t give the specific java tutorials names other then just numbers. I can definitely understand why my videos would be hard for some people to grasp because I go very fast. I try to make up for that by recovering topics that people are struggling with.

      For best results it helps to print out the code and take notes as you watch. Then if you have any questions you can pass them to me and then write out the answers in your own words.

      Sorry the tutorials didn’t work for you.


  17. Sham says:

    Hello Derek,
    I think your tutorial looks perfect for people who already played around with basic java concepts and i understand it would be too difficult for you to teach examples on each basic concept after you worked for 30 years in the industry. I would contradict myself with my point, when i talk about C tutorial where you teach all such basics, instead of going in depth ):

    May be i will come to this tutorial after i go to another java tutorial which teaches all such building blocks separately.

  18. lexi says:

    I write my code according to yours, but it doesn’t work. Can you help me solve it?

    public class View extends JFrame{
    JFrame frame;
    JTable table;
    JButton makeAppointment;
    public Login3Doctor( String[][] viewInfo,String[] columns){

    DefaultTableModel dTableModel = new DefaultTableModel(viewInfo, columns){
    public Class getColumnClass(int column) {
    Class returnValue;

    // Verifying that the column exists (index > 0 && index = 0) && (column < getColumnCount())) {
    returnValue = getValueAt(0, column).getClass();
    } else {

    // Returns the class for the item in the column

    returnValue = Object.class;
    return returnValue;

    frame=new JFrame();

    table=new JTable(dTableModel);
    table.setFont(new Font("Serif", Font.PLAIN, 20));

    TableColumn col1 = table.getColumnModel().getColumn(0);

    TableColumn col2 = table.getColumnModel().getColumn(1);

    TableColumn col3 = table.getColumnModel().getColumn(2);

    TableColumn col4 = table.getColumnModel().getColumn(2);

    JScrollPane scrollPane = new JScrollPane(table);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(800, 500);


    public static void main(String[] args){
    String[][] b={{"s","m","10","xixi","ha"},
    String[] c={"name","sex","age","lkj","4342"};
    Login3Doctor v=new Login3Doctor(b,c);



  19. sateesh says:

    Can we use text file instead of mysql database….
    and we have to get same as now…

    if so,pls help me for this code,
    i’ve already written the code,but its not giving the contents of the file as columns,

    soo,pls help me..
    pls respond quickly…

  20. Mufhim says:

    Hi Derek,
    I just wanted to say thank you so much for all the effort you put in! I’m a first year CS student and I learn faster from you than my lecturers. I’m a long time subscriber, first time commenter though. hehe.

    Thanks again! I just wish I could verbally express the extent of my gratitude.


    • Derek Banas says:

      Hi Mufhim,

      Thank you 🙂 I’m glad you are finding the videos useful. Many more are coming.

      • Anonymous says:

        Hi Derek

        Thanks for the great tutorials. Just one question please. I get an error on line 045.
        returnValue = getValueAt(0, column).getClass();

        -what does the 0 represent?

      • Bob says:

        Thanks very much Derek for the series. They are great. I just have one question please.
        Line 045 what does 0 represent in the statement
        returnValue = getValueAt(0, column).getClass();

Leave a Reply

Your email address will not be published.