Leon Anavi
IT Tips && Tricks

Java

Created: 16.07.2009 08:45 Last Modified: 18.08.2009 17:33 Views: 10252
Keywords: DefaultTableModel, getSelectedColumn, JTable, swing

JTable Basics

JTable is among the most complicated swing class. I am posting some hints for rookies which can save time and irritation.

How to disable user input at a table cell?

Override method isCellEditable and make sure it will always return a false value. Example:
javax.swing.JTable jMyTable = new javax.swing.JTable()
{
    public boolean isCellEditable(int rowIndex, int colIndex) 
    {
        return false; 
    }
};

How to add columns and rows to a table?

Each JTable instance has a model which manages columns and rows:
import javax.swing.table.DefaultTableModel;
// * * *
//Set table model
DefaultTableModel TblModel = new DefaultTableModel();
jMyTable.setModel(TblModel);
//Add some columns
TblModel.addColumn("name");
TblModel.addColumn("age");
//Add a row with index 0
m_TableModel.insertRow(0, new Object[] {"leon", "23"} );

How to get user choice?

Methods setRowSelectionAllowed, setColumnSelectionAllowed and setCellSelectionEnabled of class JTable should be used to determine what can be selected by the user. To retrieve user choice methods getSelectedColumn and getSelectedRow should be used. Both of them return integer value of column/row index. Example:
//the package is used for showing messages to user
import javax.swing.JOptionPane;
//* * *

//Allow selection of a row
jMyTable.setRowSelectionAllowed(true);
// * * *
//Get id of the selected row
int nSelectedRow = jTable1.getSelectedRow();
//Show a message box with the index
JOptionPane.showMessageDialog(null, Integer.toString(nSelectedRow) );

Further reading:

How to Use Tables

Class reference:

Class JTable
Class DefaultTableModel


  Home | About | Contact | Disclaimer | Sitemap © 2009-2022 Leon Anavi. All rights reserved.