Pages

Showing posts with label JTable. Show all posts
Showing posts with label JTable. Show all posts

Wednesday, 6 February 2013

My own TableModel (swing)

I think every java beginner encounters with this problem. How to create and to edit a JTable instance. I met this challenge as well. My first approach was simple. It was easy to choose DefaultTableModel 

 
   private static void createTable(){
       DefaultTableModel model = new DefaultTableModel();
       JTable table = new JTable(model);  
       //#1st - table constructor with a TableModel argument 
       //table = new JTable();  
       //#2 - i can add a TableModel later  
       //using setModel(model) method
       //table.setModel(model);

       Vector column1 = new Vector(); /Vector as a table column
       column1.add("data1");
       column1.add(" "); //column1 has two rows
       
       Vector column2 = new Vector();
       column2.add("data2"); //column2 has two rows
       
       model.addColumn("First", column1); 
       //model has maximum number of columns (two) 
       model.addColumn("Second", column2); 
       model.setValueAt("Change", 1, 1);
       
       table.setAutoCreateRowSorter(true); //autosorting
       //table.setSelectionMode(0);
       
   }