Sunday, 10 November 2013

Creating a JTable in Swing Effortlessly - Example

Screenshot of JTable created without effort
Here is a 3-line code that creates the type of JTable you might just be expecting as a starter. JTable class is quite terrific because it looks big, Lab Dab!! The first time I saw it, I was frightened, did you? However, the great thing is some of the constructors especially the one that takes rows and columns and row data and column data are quite simple to learn.

As this is a starter program, I didn't discuss any of the methods of the JTable rather I focused on creating a JTable using the simple row-data and column data constructor and displaying that data. This program, though not exhaustive will give you a kickstart that will remove the entire fear (if you have) about JTable and help you recognize that learning JTable is as easy as eating a cheese burger.


import javax.swing.*;
import java.awt.*;
class JTableExample extends JFrame
{
JTable t;
JScrollPane js;
String[][] rowData=    {
                    {"101","Rama","10000"},
                    {"102","Soma","20000"},
                    {"103","Raju","30000"},
                    {"104","Moju","40000"},
                    {"105","Kotu","50000"},
                    {"106","Potu","60000"}
                    };
String[] colNames=    {"ID Number","Name","Salary"};

    public JTableExample()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("JTable Example in Swing");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
      
        t=new JTable(rowData,colNames);
      
        js=new JScrollPane(t);
      
      
        setSize(400,400);
        setLocationRelativeTo(null);
        setVisible(true);
        add(js);
    }
   
    public static void main(String args[])
    {
        SwingUtilities.invokeLater(new Runnable(){
            public void run()
            {
            new JTableExample();
            }
        });
    }
}

The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)


“Obstacles only delay success; they don't stop it.” - Gowtham Gutha

No comments:

Post a Comment