Java


Java Tutorial


Admission Enquiry Form

  

Java Swing JTable

Java Swing JTable

The JTable class is a part of Java Swing Package which is used to show the data in tabular form.A JTable having rows and columns which is used to display two-dimensional data.

Constructors used with JTable

Type of Constructor Constructor Description
JTable()This method creates a table with empty cells.
JTable(int rows, int cols))This method creates a table of size rows and cols.
JTable(Object[][] rows, Object[] columns)Using this method a table is created with the specified name where Object[] Column defines the column names. .



The following example creates a JTable.

Example

JTable table=new JTable();

Basic Methods of JTable class :

Method NameDescription
addColumn(TableColumn []column)This method adds a column at the end of the JTable.
getRowCount()Gets the current total number of the rows in the JTable.
getColumns()Gets the current total number of the columns in the JTable.
setValueAt(Object value, int row, int col) Sets the cell value as ‘value’ for the position row, col in the JTable.
TableModel getModel()Gets the TableModel whose data is displayed by JTable.



Example of JTable with JTable(Object[][] rows, Object[] columns)

import javax.swing.*;
class TableExample extends JFrame
{
    JTable jt;
    TableExample()
    {
        String data[][]={ {"Neha","10","20000"},
                {"Priya","20","30000"},
                {"Sunil","30","50000"}};
        String fields[]={"NAME","ROLLNO","FEE"};
        jt=new JTable(data,fields);
        jt.setBounds(30,40,200,300);
jt.setBackground(Color.PINK);
        JScrollPane sp=new JScrollPane(jt);
        add(sp);
        setTitle("JTable Example");
        setSize(300,300);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
public class JTableExample
{
public static void main(String[] args)
{
TableExample table= new TableExample();
}
}


Output

The code above will display :



Example of JTable with DefaultTableModel

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;

class TableExample extends JFrame {
JTable jt;
DefaultTableModel dtm;
TableExample()
{
String data[][] = {{"Neha", "10", "20000"},
{"Priya", "20", "30000"},
{"Sunil", "30", "50000"}};
String fields[] = {"NAME", "ROLLNO", "FEE"};
dtm = new DefaultTableModel(data, fields);
jt = new JTable(dtm);
jt.setBackground(Color.PINK);
jt.setBounds(30, 40, 200, 300);
JScrollPane sp = new JScrollPane(jt);
add(sp);
setTitle("JTable Example");
setSize(300, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public class JTableExample
{
public static void main(String[] args)
{
TableExample table= new TableExample();
}
}



Output

The code above will display :