Constructors of the JTable class:
-JTable()
creates an empty table with default data, column, and selection models.
-JTable(int rows, int columns)
creates an empty table with the specified number of rows and columsn using DefaultTableModel.
-JTable(Object[][] rowData, Object[] columnNames)
creates table with data in rows taken from the two-dimensional array, rowData and column names taken from the array, columnNames.
-JTable(TableModel dm)
creates table to display data of the TableModel, dm with default column and selection models.
-JTable(TableModel dm, TableColumnModel cm)
creates table to display data of the TableModel, dm with column names taken from TableColumnModel, cm and default selection model.
-JTable(TableModel dm, TableColumnModel cm, ListSelectionModel)
creates table to display data of the TableModel, dm with column names taken from TableColumnModel, cm, and selection model, sm.
-JTable(Vector rowData, Vector columnNames)
creates table to display data of the vector of vectors, rowData, and the column names,columnNames.
In the example below, data are retrieved from the SQLite database called sales.db. In the database, the tblcustomers table is created and sample data are inserted when the program initially runs. The DefaultTableModel, dm is created and some column names are added. Then The sample data are retrieved immediately to populate the DefaultTableModel, dm before it is added to the JTable, table object.
import java.awt.FlowLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.*;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
class MainForm extends JFrame{
TableColumnModel colmodel;
DefaultTableModel model;
DataManager dm;
MainForm(){
//setExtendedState(JFrame.MAXIMIZED_BOTH);
setTitle("JTable");
setSize(500,300);
setLayout(new FlowLayout());
dm=new DataManager();
//add sample data to the sqlite database
addSampleDataToDatabase();
//create data model for a table component
model=new DefaultTableModel();
//add column names to the model
model.addColumn("ID");
model.addColumn("Name");
model.addColumn("Sex");
model.addColumn("Address");
model.addColumn("Email");
model.addColumn("Phone");
//read sample data from the database and place them in the model
dm.getData(model);
//create a table object
JTable table = new JTable(model);
JScrollPane scrollpane = new JScrollPane(table);
add(scrollpane);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
try {
dm.closeConnection();
} catch (SQLException se) {
se.printStackTrace();
}
System.exit(0);
}
});
setVisible(true);
}
public void addSampleDataToDatabase(){
dm.insertSampleData(1, "Sok Chan","F","#444,st.933,Phnom Penh","sk.chan@gmail.com","855334543");
dm.insertSampleData(2, "Thida Vin","F","#23,st.103,Kampot","vin_thida@gmail.com","855135547");
dm.insertSampleData(3, "Chea Som","M","#476,st.883,Phnom Penh","chea_som@yahoo.com","855988454");
}
}
class DataManager {
Connection c = null;
Statement stm=null;
DataManager(){
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:sales.db");
stm=c.createStatement();
String sql="CREATE TABLE tblcustomers(Id INT PRIMARY KEY, Name TEXT NOT NULL, Sex TEXT NOT NULL,"+
" Address TEXT NOT NULL, Email TEXT NOT NULL, Phone TEXT NOT NULL)";
stm.executeUpdate(sql);
} catch ( Exception e ) {
e.printStackTrace();
System.exit(0);
}
}
public void insertSampleData(int id,String name, String sex, String address,String email, String phone){
String sqlinsertion="INSERT INTO tblcustomers(Id,Name,Sex,Address,Email,Phone) VALUES("+id+",'"
+sex+"','"+name+"','"+address+"','"+email+"','"+phone+"')";
try{
stm.executeUpdate(sqlinsertion);
}catch(SQLException se){se.printStackTrace();}
}
public void getData(DefaultTableModel datamodel){
String sqlselection="SELECT * FROM tblcustomers";
try{
ResultSet result=stm.executeQuery(sqlselection);
if(result!=null){
while(result.next()){
datamodel.addRow(new Object[]{result.getInt("Id"),result.getString("Name"),result.getString("Sex"),result.getString("Address"),result.getString("Email"),result.getString("Phone")});
}
}
}catch(SQLException se){se.printStackTrace();}
}
public void closeConnection() throws SQLException{
stm.close();
c.close();
}
}
public class CusList{
public static void main(String[] args){
new MainForm();
}
}
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.*;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
class MainForm extends JFrame{
TableColumnModel colmodel;
DefaultTableModel model;
DataManager dm;
MainForm(){
//setExtendedState(JFrame.MAXIMIZED_BOTH);
setTitle("JTable");
setSize(500,300);
setLayout(new FlowLayout());
dm=new DataManager();
//add sample data to the sqlite database
addSampleDataToDatabase();
//create data model for a table component
model=new DefaultTableModel();
//add column names to the model
model.addColumn("ID");
model.addColumn("Name");
model.addColumn("Sex");
model.addColumn("Address");
model.addColumn("Email");
model.addColumn("Phone");
//read sample data from the database and place them in the model
dm.getData(model);
//create a table object
JTable table = new JTable(model);
JScrollPane scrollpane = new JScrollPane(table);
add(scrollpane);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
try {
dm.closeConnection();
} catch (SQLException se) {
se.printStackTrace();
}
System.exit(0);
}
});
setVisible(true);
}
public void addSampleDataToDatabase(){
dm.insertSampleData(1, "Sok Chan","F","#444,st.933,Phnom Penh","sk.chan@gmail.com","855334543");
dm.insertSampleData(2, "Thida Vin","F","#23,st.103,Kampot","vin_thida@gmail.com","855135547");
dm.insertSampleData(3, "Chea Som","M","#476,st.883,Phnom Penh","chea_som@yahoo.com","855988454");
}
}
class DataManager {
Connection c = null;
Statement stm=null;
DataManager(){
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:sales.db");
stm=c.createStatement();
String sql="CREATE TABLE tblcustomers(Id INT PRIMARY KEY, Name TEXT NOT NULL, Sex TEXT NOT NULL,"+
" Address TEXT NOT NULL, Email TEXT NOT NULL, Phone TEXT NOT NULL)";
stm.executeUpdate(sql);
} catch ( Exception e ) {
e.printStackTrace();
System.exit(0);
}
}
public void insertSampleData(int id,String name, String sex, String address,String email, String phone){
String sqlinsertion="INSERT INTO tblcustomers(Id,Name,Sex,Address,Email,Phone) VALUES("+id+",'"
+sex+"','"+name+"','"+address+"','"+email+"','"+phone+"')";
try{
stm.executeUpdate(sqlinsertion);
}catch(SQLException se){se.printStackTrace();}
}
public void getData(DefaultTableModel datamodel){
String sqlselection="SELECT * FROM tblcustomers";
try{
ResultSet result=stm.executeQuery(sqlselection);
if(result!=null){
while(result.next()){
datamodel.addRow(new Object[]{result.getInt("Id"),result.getString("Name"),result.getString("Sex"),result.getString("Address"),result.getString("Email"),result.getString("Phone")});
}
}
}catch(SQLException se){se.printStackTrace();}
}
public void closeConnection() throws SQLException{
stm.close();
c.close();
}
}
public class CusList{
public static void main(String[] args){
new MainForm();
}
}
DefaultTableCellRenderer class is used to paint the cells and format the values of the cells. The code fragment below applies red background color and bold font to all cells in even columns and light gray background color and normal font to all cells in odd columns of the table. You can apply a cell renderer object to a column of the table by using the setCellRenderer( TableCellRenderer cellRenderer) method of the table column object.
TableColumn column = null;
for (int i = 0; i < model.getColumnCount(); i++) {
column = table.getColumnModel().getColumn(i);
if(i%2==0){
column.setPreferredWidth(100);
MyCellRenderer cellRenderer=new MyCellRenderer(Color.RED, new Font("Arial",Font.BOLD,12));
column.setCellRenderer(cellRenderer);
}
else
{
column.setPreferredWidth(100);
MyCellRenderer cellRenderer=new MyCellRenderer(Color.LIGHT_GRAY,new Font("Arial",Font.PLAIN,12));
column.setCellRenderer(cellRenderer);
}
}
MyCellRenderer is a class that extends the DefaultTableCellRenderer class.
class MyCellRenderer extends DefaultTableCellRenderer {
Color bgColor=null;
Font font=null;
public MyCellRenderer(Color c,Font f) {
super();
bgColor=c;
font=f;
}
public void setValue(Object value) {
setText(value.toString());
setBackground(bgColor);
setFont(font);
}
}
for (int i = 0; i < model.getColumnCount(); i++) {
column = table.getColumnModel().getColumn(i);
if(i%2==0){
column.setPreferredWidth(100);
MyCellRenderer cellRenderer=new MyCellRenderer(Color.RED, new Font("Arial",Font.BOLD,12));
column.setCellRenderer(cellRenderer);
}
else
{
column.setPreferredWidth(100);
MyCellRenderer cellRenderer=new MyCellRenderer(Color.LIGHT_GRAY,new Font("Arial",Font.PLAIN,12));
column.setCellRenderer(cellRenderer);
}
}
MyCellRenderer is a class that extends the DefaultTableCellRenderer class.
class MyCellRenderer extends DefaultTableCellRenderer {
Color bgColor=null;
Font font=null;
public MyCellRenderer(Color c,Font f) {
super();
bgColor=c;
font=f;
}
public void setValue(Object value) {
setText(value.toString());
setBackground(bgColor);
setFont(font);
}
}
By using the DefaultTableCellRender class, you can apply styles to the cells of a column or many columns. You can also use this class to style the column headers. However, you need to use the setHeaderRenderer
(TableCellRenderer render method) of a column object to specify the renderer for the columns. The below code fragment does this task.
TableColumn column = null;
MyHeaderRenderer headerRenderer=new MyHeaderRenderer
(Color.RED, new Font("Arial",Font.BOLD,15));
for (int i = 0; i < model.getColumnCount(); i++) {
column = table.getColumnModel().getColumn(i);
column.setHeaderRenderer(headerRenderer);
}
MyHeaderRenderer is a class that extends the DefaultTableCellRenderer class.
class MyHeaderRenderer extends DefaultTableCellRenderer {
Color bgColor=null;
Font font=null;
public MyHeaderRenderer(Color c,Font f) {
super();
bgColor=c;
font=f;
}
public void setValue(Object value) {
setText(value.toString());
setBackground(bgColor);
setFont(font);
}
}
MyHeaderRenderer headerRenderer=new MyHeaderRenderer
(Color.RED, new Font("Arial",Font.BOLD,15));
for (int i = 0; i < model.getColumnCount(); i++) {
column = table.getColumnModel().getColumn(i);
column.setHeaderRenderer(headerRenderer);
}
MyHeaderRenderer is a class that extends the DefaultTableCellRenderer class.
class MyHeaderRenderer extends DefaultTableCellRenderer {
Color bgColor=null;
Font font=null;
public MyHeaderRenderer(Color c,Font f) {
super();
bgColor=c;
font=f;
}
public void setValue(Object value) {
setText(value.toString());
setBackground(bgColor);
setFont(font);
}
}
If don't want to allow cells editing in a column or you want to create your own editor for those cells, you can use the DefaultCellEditor to do these tasks. In the code fragment below, all cells in the first columns (index 0) are not allowed to edit. All cells in the third column (index 2) use a drop down list as its editor.
TableColumn column = null;
for (int i = 0; i < model.getColumnCount(); i++) {
column = table.getColumnModel().getColumn(i);
if(i==0){
column.setPreferredWidth(100);
JTextField txt=new JTextField();
txt.setEditable(false);
DefaultCellEditor editor=new DefaultCellEditor(txt);
column.setCellEditor(editor);
}
else if(i==2)
{
column.setPreferredWidth(100);
JComboBox box=new JComboBox();
box.addItem("M");
box.addItem("F");
DefaultCellEditor editor=new DefaultCellEditor(box);
column.setCellEditor(editor);
}
}
for (int i = 0; i < model.getColumnCount(); i++) {
column = table.getColumnModel().getColumn(i);
if(i==0){
column.setPreferredWidth(100);
JTextField txt=new JTextField();
txt.setEditable(false);
DefaultCellEditor editor=new DefaultCellEditor(txt);
column.setCellEditor(editor);
}
else if(i==2)
{
column.setPreferredWidth(100);
JComboBox box=new JComboBox();
box.addItem("M");
box.addItem("F");
DefaultCellEditor editor=new DefaultCellEditor(box);
column.setCellEditor(editor);
}
}