Monday, July 2, 2012

Creating a simple JTable

Program Description:

Today we are going to create a very simple JTable in Java with inputs which I think this is the shortest, easy-to-understand JTable program you can find in the internet. In this program, there are only three things you need to observe 1.) The Column Names 2.) The Input Data 3.) Adding Scroll Bar. This program will show you how to create those things and add them in the JTable so you can come up with an output similar to the screenshot below and if you have finally understood the whole code, you are now ready to learn the complicated parts of this components. So I hope you'll find this very helpful and don't forget to add comments.

Output:
Code:

/**
* File: simpleJTable.java
* Tiltle: Creating a simple JTable
* Author: http://java-code-complete.blogspot.com/
*/

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;

public class simpleJTable extends JFrame {

//Initializing the Column Names of the Table
String columnNames[] = {"First Name","Middle Name","Last Name"};

//Initializing the Specific Data input of the Table
Object data[] [] = {{"Jack","Denzil","Smith"},{"Robert","Smack","Gregory"},{"Stephen","Den","Stash"},{"Evelyn","Baaclo","Kontes"}};

//Setting up GUI
public simpleJTable() {

//Setting up the Title of the Window
super("Creating a simple JTable");

//Creating a JTable with its property
JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);

//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);

//Exit Property of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Setting up the container ready for the components to be added.
Container pane = getContentPane();
setContentPane(pane);

//Setting up the container layout
GridLayout grid = new GridLayout(1,0);
pane.setLayout(grid);

//Adding the Component JScrollPane so the JTable can be visible in the container
//with Scroll Bar on the right side if JTable input data exceeds the visible count
pane.add(scrollPane);

/**Set all the Components Visible.
* If it is set to "false", the components in the container will not be visible.
*/
setVisible(true);
pack(); //Group all the components together
}

//Main Method
public static void main (String[] args) {
simpleJTable pjtf = new simpleJTable();
}
}

No comments:

Post a Comment