Updated July 10, 2023
Introduction to JTable in Java
In Java, JTable is used to edit or display 2-D data which consists of rows and columns. It is almost similar to a spreadsheet that contains data in a tabular form. JTable can be created by instantiating the class javax.swing.JTable. Let us look into syntax, constructor, and methods of JTable in Java in detail.
Syntax of JTable in Java:
JTable jt=new JTable();
Constructors of JTable in Java
JTable in Java has three constructors. They are:
- JTable(): A new table will be created with empty cells.
- JTable(int r, int c): A table will be created with the size as r*c.
- JTable(Object[ ][ ] d, Object [ ]col): A table will be created with the specified data where []col describes the names of column.
Methods of JTable in Java
The following are the most common methods of JTable in Java:
- addColumn (TableColumnc): A column c will be added to the column array end of the JTable column model.
- clearSelection (): The columns and rows which are selected will be deselected.
- columnAdded (TableColumnModelEventev): When a column is added to the column model of the table, this method will be called.
- columnMoved (TableColumnModelEventev): When a column repositions, this method will be called.
- columnMarginChanged (ChangeEventev): When a column repositions due to margin change, this method will be called.
- columnRemoved (TableColumnModelEvente): This method will be called when a column is removed from the column model of the table.
- columnSelectionChanged (ListSelectionEventev): When the selection model is changed, this method will be called.
- convertColumnIndexToModel (int viewColumnIndex): Column in the view at viewColumnIndex will be mapped to the column index in the table model.
- convertColumnIndexToView (int modelColumnIndex): The column index in the table model at modelColumnIndex will be mapped to the view.
- getSelectedColumn (): The index of the selected column which is selected first will be returned. It no column is selected, -1 will be returned.
- getSelectedColumnCount (): A count of selected columns will be returned.
- getSelectedColumns (): The index of the selected columns will be returned.
- getSelectedRow (): The index of the selected row which is selected first will be returned. It no row is selected, -1 will be returned.
- getSelectedRowCount (): Count of selected rows will be returned.
- getSelectedRows (): The index of selected rows will be returned.
- removeColumnSelectionInterval (int i0, int i1 ): Columns from index 0 to 1 will be deselected.
- isCellEditable (int r, int c): If the cell in the specified row and column is editable, true will be returned.
- removeColumn (TableColumnc): Column c will be removed from the table’s column array.
- isCellSelected (int R, int C): If the mentioned index is in the valid range of columns and rows and also, that position is selected, true will be returned.
- isEditing (): If the cell is editing, true will be returned.
- isRowSelected (int r): If the mentioned index is in the valid range of rows and also, that row is selected, true will be returned.
- isColumnSelected (int c): If the mentioned index is in the valid range of columns and also, that row is selected, true will be returned.
- moveColumn (int c, int tc): Column c gets moved to the position where column tc is occupied.
Program to Implement JTable in Java
Now, let us see different JavaFX programs to implement JTable in java.
Program #1 – Program to display a simple JTable
Code:
//Java program to demonstrate JTable
//import the following swing packages
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
//sample class
public class JavaTableExample {
// declare frame
JFrame fr;
// declare Table
JTable jt;
// Constructor of the class
JavaTableExample()
{
// initiallization of the frame
fr = new JFrame();
// set Title for the frame
fr.setTitle("JTable Sample");
// Data that will be displayed in JTable
String[][] d = {
{ "Sam", "29" ," Twinkle House" },
{ "Anna Sam", " 27 ", "Happy Villa" },
{ "Iza Norah", " 4 ", "Happy house" },
};
// Names of the column
String[] cn = { "Name", "Age", "House Address" };
// JTable initialization
jt = new JTable(d, cn);
//set bounds for JTable
jt.setBounds(30, 40, 200, 300);
// add it to the JScrollPane
JScrollPane jsp = new JScrollPane(jt);
fr.add(jsp);
// set the Size of frame
fr.setSize(500, 200);
//set the frame visibility as true
fr.setVisible(true);
}
// main method
public static void main(String[] args)
{
new JavaTableExample();
}
}
Output:
A table will be displayed with the data mentioned in the program.
Example #2 – Program to implement the JTable in java with a print button
Code:
//java program to create a java table with a print option in it
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
public class JavaTableExample {
public static void main(String args[]) {
//rows of the table
final Object r[][] = {
{"Adam", "13" , "Doctor"},
{"Anna", "21" ,"Engineer"},
{"Annamu", "31" ,"Technician"},
{"Iza", "41" ,"Physician"},
{"Norah", "11" , "Author"},
{"Naashy", "12" ,"Artist"},
{"Poosa", "33" ,"Actor"},
{"Pichi", "14" ,"Author"},
{"Kunjol", "31" ,"Police"},
{"Thukidi", "12" ,"Doctor"},
{"Sam", "13" , "Engineer"},
{"Kukku", "24" ,"Technician"},
{"Remya", "31" ,"Engineer"},
{"Radha", "42" ,"Lawyer"},
{"Harini", "43", "Artist"},
{"Vaibhav", "44" , "Engineer"},
};
//headers of the column
final Object h[] = {"Name", "Age" ,"Occupation"};
//create a frame
JFrame fr = new JFrame(" Printing table");
// close operation
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//create a table
final JTable tb = new JTable(r, h);
//create scroll pane
JScrollPane sp = new JScrollPane(tb);
fr.add(sp , BorderLayout.CENTER);
//create a button
JButton button = new JButton("click this button to Print");
//set an action
ActionListener act = new ActionListener() {
public void actionPerformed(ActionEvent e) {
//exception handling
try {
tb.print();
} catch (PrinterException pe) {
System.err.println("Error printing: " + pe.getMessage());
}
}
};
button.addActionListener(act);
fr.add(button, BorderLayout.SOUTH);
//set the size
fr.setSize(300, 150);
fr.setVisible(true);
}
}
Output:
On Executing the code, a table, as shown above, will be displayed. It is clearly seen that a button ‘Click this button to Print’ is on the bottom of the table. On clicking it, a popup to print the page will be shown.
Conclusion
JTable in Java is almost similar to a spreadsheet that consists of rows and columns. It is mainly used to modify or show 2-D data that are available in those rows and columns.
Recommended Articles
This is a guide to JTable in Java. Here we discuss the basic concept, constructor and methods of JTable in Java along with program to implement. You may also look at the following articles to learn more –