Thursday, June 20, 2013

Using AbstractTableModel

In this post, I explain how to make a JTable using AbstractTableModel

Using AbstractTableModel is very straight foward, so I will just post
a source code that one can use as a basic form like DefaultTableModel

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jtbl_ex;

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Lee
 */
public class TableOne extends JPanel{
    
    private JTable table;
    private JScrollPane scrollPane;
    private AbstractTableModel model;
    
    // data for the table
    private Object[][] data = {
        {null, null, null, null},
        {null, null, null, null},
        {null, null, null, null},
        {null, null, null, null}
    };

    // column names for the table
    private String[] columnNames = {
        "Name1", "Name2", "Name3", "Name4"
    };
    
    
    
    public TableOne() {
        // set the Layout for the JPanel
        super(new BorderLayout());
       
        initComponents();
    }
    
    public void initComponents() {
        // Initialize the Abstract Table Model
        model = new MyTableModel();
        
        // Add the model to the JTable
        table = new JTable(model);
        
        // Add the table to the JScrollPane
        scrollPane = new JScrollPane(table);
        
        // Add the scrollPane to the JPanel
        this.add(scrollPane);
    }
    
    // Define the model for the table using AbstractTableModel
    class MyTableModel extends AbstractTableModel{
        
        // Decide the row count according to the data length
        @Override
        public int getRowCount() {
            return data.length;
        }

        // decide the column count according to the columnNames length
        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        // put the data values into the table. 
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return data[rowIndex][columnIndex];
        }
        
        // put the columnNames values into the table column names
        @Override
        public String getColumnName(int col){
            return columnNames[col];
        }
        
        // set if the cells in the table are editable. 
        // In this example, all the cells are editable
        @Override
        public boolean isCellEditable(int row, int col) {
            return true;
        }
         
        // this is for data change. 
        @Override
        public void setValueAt(Object value, int row, int col) {
            data[row][col] = value;
            fireTableCellUpdated(row, col);
        }

        /* 
         * JTable uses this method to determine the default renderer/  
         * editor for each cell.  If we didn't implement this method,  
         * then the last column would contain text ("true"/"false"),     
         * rather than a check box.  (From oracle JTable tutorial)
        */
        @Override
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

    }
    
    /**      
     * Create the GUI and show it.  
     * For thread safety,     
     * this method should be invoked from the     
     * event-dispatching thread.    
     * (from Oracle table tutorial)
     */
    private static void createAndShowGUI() {     
        //Create and set up the window.      
        JFrame frame = new JFrame("TableRenderDemo");    
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
        
        //Create and set up the content pane.        
        TableOne newContentPane = new TableOne();      
        newContentPane.setOpaque(true); //content panes must be opaque    
        frame.setContentPane(newContentPane);         
        
        //Display the window.    
        frame.pack();      
        frame.setVisible(true);    
    } 
    
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:       
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }
}


for more information about AbstractTableModel,  check
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html

No comments:

Post a Comment