Thursday, 26 February 2015

Use of JTable in java using DefaultTableModel

//A program to use table using JTable in java with the help of DefaultTableModel

//Note: Add more values to the table either in the code or by using GUI edit mode






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

class TableDemo extends JFrame{
private DefaultTableModel dm;
private JTable table;

public TableDemo(String title){
super(title);
setLayout(new GridLayout(1,1));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
initialize();
pack();
}

public void initialize(){
String[] column_name = {"S.No.","Name","Country","State"};
dm = new DefaultTableModel(column_name,10);
table = new JTable(dm);
JScrollPane scroll = new JScrollPane(table);
add(scroll);

//Sorts the table according the column clicked by the user
table.setAutoCreateRowSorter(true);

String[] record = {"1" , "Mohit" , "India" , "Rajasthan"};
dm.insertRow(0,record);
}

public static void main (String[] args) {
new TableDemo("Table Demo");
}


}

No comments:

Post a Comment