JTable in Java with Example
Table of Contents
a) Introduction to JTable
b) Constructor of JTable
c) Example with Source Code
d) Output
***************
Introduction:
JTable
is a swing component. It is used to display data in the form of rows and
columns. It helps to arrange the data in such manner which helps the user to interact
with the program more easily. If a table is directly added to frame, column
headings and scroll bar does not appear. Therefore, we need to use
JScrollBarPane class in-order to work with JTable.
JTable has a one constructor i.e. JTable(Object [][]data, String columns).
Its constructor takes two argument which is of Object type and String type.
Let us create the JTable;
Source Code:
/*
* To change this license
header, choose License Headers in Project Properties.
* To change this template
file, choose Tools | Templates
* and open the template
in the editor.
*/
/**
*
* @author AnkitPC
*/
import javax.swing.*;
import java.awt.*;
public class JTableDemo {
JFrame f;
JScrollPane jsp;
JTable t;
JTableDemo(){
f=new
JFrame("Table Demo");
//setting size
f.setSize(600,400);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//setting layout
f.setLayout(new
BorderLayout());
Object[][]data={
{1,"Ankit",20000},
{2,"Anil",10000},
{3,"Dipesh",12000},
{4,"Shraddha",14000},
{5,"Pratik",11500}
};
String
[]cols={"ID","Name","Salary"};
t=new
JTable(data,cols);
//
t.setEnabled(false);
// t.setSelectionForeground(Color.yellow);
//t.setSelectionBackground(Color.CYAN);
//
t.setGridColor(Color.BLUE);
jsp=new
JScrollPane(t);
//adding the component
f.add(jsp);
f.setVisible(true);
}
public static void
main(String[] args) {
//calling the
constructor
new JTableDemo();
}
}
Output:
The above output shows the JTable.
********************************
Previous Lessons;
User Defined Dialog Box
Open and Save Dialog Box
Dialog Box in Java with Examples
JComboBox and JList
Key Event
Focus Event
Different Ways to Handle Event
Open and Save Dialog Box
Dialog Box in Java with Examples
JComboBox and JList
Key Event
Focus Event
Different Ways to Handle Event
0 Comments