Jdbc abstract Jtable model problem

Hi,
I am trying to write a program that displays the content of a database in a jtable.
So far the displaying is working, but Im having trouble with adding, deleting and modifying the jtable.
Im working on the add method first. Its supposed to add a blank row, but it just adds the last row instead.
Heres the source:
// new class. This is the table model
import javax.swing.table.*;
import java.sql.*;
import java.util.Vector;
import javax.swing.JTable;
public class MyTableModel extends AbstractTableModel {
Connection con;
Statement stat;
ResultSet rs;
int li_cols = 0;
Vector allRows;
Vector row;
Vector newRow;
Vector blankRow;
Vector colNames;
String dbColNames[];
String pkValues[];
String tableName;
ResultSetMetaData myM;
String pKeyCol;
Vector deletedKeys;
Vector newRows;
boolean ibRowNew = false;
boolean ibRowInserted = false;
MyTableModel(){
try{
Class.forName("com.mysql.jdbc.Driver");
catch (ClassNotFoundException e){
System.out.println("Cannot Load Driver!");
try{
String url = "jdbc:mysql://localhost:3306/aubrey?";
con = DriverManager.getConnection(url,"Dude1", "supersecret");
stat = con.createStatement();
rs = stat.executeQuery("SELECT * from COFFEES");
deletedKeys = new Vector();
newRows = new Vector();
myM = rs.getMetaData();
tableName = myM.getTableName(1);
li_cols = myM.getColumnCount();
dbColNames = new String[li_cols];
for(int col = 0; col < li_cols; col ++){
dbColNames[col] = myM.getColumnName(col + 1);
allRows = new Vector();
while(rs.next()){
newRow = new Vector();
for(int i = 1; i <= li_cols; i++){
newRow.addElement(rs.getObject(i));
} // for
allRows.addElement(newRow);
} // while
catch(SQLException e){
System.out.println(e.getMessage());
public Class getColumnClass(int col){
return getValueAt(0,col).getClass();
public boolean isCellEditable(int row, int col){
if (ibRowNew){
return true;
if (col == 0){
return false;
} else {
return true;
public String getColumnName(int col){
return dbColNames[col];
public int getRowCount(){
return allRows.size();
public int getColumnCount(){
return li_cols;
public Object getValueAt(int arow, int col){
row = (Vector) allRows.elementAt(arow);
return row.elementAt(col);
public void setValueAt(Object aValue, int aRow, int aCol) {
Vector dataRow = (Vector) allRows.elementAt(aRow);
dataRow.setElementAt(aValue, aCol);
fireTableCellUpdated(aRow, aCol);
public void updateDB(){}
public void addRow(){
     newRow.addElement(blankRow);
     int rowNumber = allRows.size();
     allRows.addElement(newRow);
     ibRowNew = true;
     this.isCellEditable(allRows.size(),0);
     System.out.println(allRows.size());
     fireTableRowsInserted(rowNumber,rowNumber);
public void deleteRow(int i){}
}And here is the code for the GUI:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class MyTableApp extends JFrame{
JTable myTable;
JButton update;
JButton insert;
JButton delete;
JPanel p;
MyTableModel tm;
JScrollPane myPane;
MyTableApp(){
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
catch(Exception e){
System.out.println("Error on look and feel");
update = new JButton("Update");
insert = new JButton("Add");
delete = new JButton("Delete");
p = new JPanel();
tm = new MyTableModel();
myTable = new JTable(tm);
myPane = new JScrollPane(myTable,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
myTable.setSelectionForeground(Color.white);
myTable.setSelectionBackground(Color.red);
myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
p.add(myPane);
p.add(update);
p.add(insert);
p.add(delete);
update.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tm.updateDB();
insert.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tm.addRow();
myTable.setEditingRow(tm.getRowCount());
myTable.setRowSelectionInterval(tm.getRowCount()-1,tm.getRowCount()-1);
delete.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int rowToDelete = myTable.getSelectedRow();
tm.deleteRow(rowToDelete);
myTable.setEditingRow(rowToDelete -1);
myTable.setRowSelectionInterval(rowToDelete -1,rowToDelete -1);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}); // end windowlistener
this.setContentPane(p);
this.setVisible(true);
this.pack();
} // constructor
public static void main (String args[]){
new MyTableApp();
} // main
} //class

When adding a row to a JTable, one should manipulate the table model. There are many examples of this on the web. Google is your friend.
Good luck.
Filestream

Similar Messages

  • How to Add and delete a row while using Abstract Table Model

    Hi,
    I need to do the following functionalities in JTable.I've done tht but a small problem.
    1. Adding a row (Using addRow() method from DefaultTableModel).
    2. Deleting a row(Using setRowCount() method from Default Table Model).
    3. Sorting the table based on the selection of column(Using TableSorter which is using AbstracTableModel).
    As the sorting is mandatory i've to change my model to Abtract Table Model
    The problem is this Abstract Table Model doesn't have any methods to Add a row or deleting a row (setRowCount()).If anybody has written any utility method for this using Abstract Table Model help me.

    Using TableSorter which is using AbstracTableModel).If your talking about the TableSorter class from the Swing tutorial, then you create the TableSorter class by passing it a TableModel. There is no reason you can't use the DefaltTableModel.
    I changed the code in TableSorterDemo as follows:
            String[] columnNames = {"First Name",
                                            "Last Name",
                                            "Sport",
                                            "# of Years",
                                            "Vegetarian"};
            Object[][] data = {
                {"Mary", "Campione",
                 "Snowboarding", new BigDecimal(1), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new BigDecimal(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new BigDecimal(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new BigDecimal(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new BigDecimal(10), new Boolean(false)}
              DefaultTableModel model = new DefaultTableModel(data, columnNames)
                   public Class getColumnClass(int c)
                        return getValueAt(0, c).getClass();
            TableSorter sorter = new TableSorter(model);
    //        TableSorter sorter = new TableSorter(new MyTableModel()); //ADDED THIS

  • JTable size problems due to layout/grid...how can I fix?

    This is my code. When the button "Modify Entries" is pressed, it shows a JTable that imports a file called, "entries.data". The items in this file can be read and saved using this program. The problem is that the table is so small when it first opens. How can I set all my buttons to the very bottom of the form and make the table take up more space at the top? It looks to me as if this layout is treating it with the same dimensions as the buttons'.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    import java.util.*;
    import java.io.*;
    public class CPT extends JPanel implements ActionListener
        protected JButton ModifyEntriesButton, ViewEntriesButton, SearchEntriesButton, SaveButton, BackButton;
        private final static String newline = "\n";
        private DefaultTableModel model;
        public CPT ()
            super (new GridLayout (10, 0));
            model = new PropertiesModel ("entries.data");
            ModifyEntriesButton = new JButton ("Modify Entries");
            ModifyEntriesButton.setVerticalTextPosition (AbstractButton.TOP);
            ModifyEntriesButton.setHorizontalTextPosition (AbstractButton.LEFT);
            ModifyEntriesButton.setToolTipText ("Click this button to modify database entries.");
            ModifyEntriesButton.setMnemonic (KeyEvent.VK_M);
            ModifyEntriesButton.setActionCommand ("ModifyEntries");
            ModifyEntriesButton.addActionListener (this);
            ViewEntriesButton = new JButton ("View Entries");
            ViewEntriesButton.setVerticalTextPosition (AbstractButton.CENTER);
            ViewEntriesButton.setHorizontalTextPosition (AbstractButton.LEFT);
            ViewEntriesButton.setToolTipText ("Click this button to add view all database entries.");
            ViewEntriesButton.setMnemonic (KeyEvent.VK_V);
            ViewEntriesButton.setActionCommand ("ViewEntries");
            ViewEntriesButton.addActionListener (this);
            SearchEntriesButton = new JButton ("Search Entries");
            SearchEntriesButton.setVerticalTextPosition (AbstractButton.BOTTOM);
            SearchEntriesButton.setHorizontalTextPosition (AbstractButton.LEFT);
            SearchEntriesButton.setToolTipText ("Click this button to search through all database entries.");
            SearchEntriesButton.setMnemonic (KeyEvent.VK_S);
            SearchEntriesButton.setActionCommand ("SearchEntries");
            SearchEntriesButton.addActionListener (this);
            SaveButton = new JButton ("Save");
            SaveButton.setVerticalTextPosition (AbstractButton.TOP);
            SaveButton.setHorizontalTextPosition (AbstractButton.RIGHT);
            SaveButton.setToolTipText ("Click this button to save database entries.");
            SaveButton.setMnemonic (KeyEvent.VK_S);
            SaveButton.setActionCommand ("Save");
            SaveButton.addActionListener (this);
            BackButton = new JButton ("Back");
            BackButton.setVerticalTextPosition (AbstractButton.BOTTOM);
            BackButton.setHorizontalTextPosition (AbstractButton.RIGHT);
            BackButton.setToolTipText ("Click this button to return to the main menu.");
            BackButton.setMnemonic (KeyEvent.VK_B);
            BackButton.setActionCommand ("Back");
            BackButton.addActionListener (this);
            add (ModifyEntriesButton);
            add (ViewEntriesButton);
            add (SearchEntriesButton);
        class PropertiesModel extends DefaultTableModel
            public PropertiesModel (String filename)
                addColumn ("Item Number");
                addColumn ("Description");
                addColumn ("Price");
                //Fill model with data from property file
                Properties props = readFile (filename);
                if (props != null)
                    Enumeration coll = props.keys ();
                    while (coll.hasMoreElements ())
                        String property = (String) coll.nextElement ();
                        String value = props.getProperty (property, "");
                        addRow (new Object[]
                            property, value
        private Properties readFile (String filename)
            try
                Properties props = new Properties ();
                props.load (new FileInputStream (filename));
                return props;
            catch (IOException ioe)
                return null;
        private boolean saveFile (String filename)
            try
                Properties props = new Properties ();
                for (int i = 0 ; i < model.getRowCount () ; i++)
                    props.put (model.getValueAt (i, 0), model.getValueAt (i, 1));
                props.store (new FileOutputStream (filename), null);
                return true;
            catch (IOException ioe)
                return false;
        public void actionPerformed (ActionEvent e)
            if ("ModifyEntries".equals (e.getActionCommand ()))
                removeAll ();
                add (new JScrollPane (new JTable (model)), BorderLayout.CENTER);
                add (SaveButton);
                add (BackButton);
                invalidate ();
                updateUI ();
            if ("ViewEntries".equals (e.getActionCommand ()))
                removeAll ();
                add (BackButton);
                invalidate ();
                updateUI ();
            if ("SearchEntries".equals (e.getActionCommand ()))
                removeAll ();
                add (BackButton);
                invalidate ();
                updateUI ();
            if ("Back".equals (e.getActionCommand ()))
                removeAll ();
                add (ModifyEntriesButton);
                add (ViewEntriesButton);
                add (SearchEntriesButton);
                invalidate ();
                updateUI ();
            if ("Save".equals (e.getActionCommand ()))
                if (saveFile ("entries.data"))
                    JOptionPane.showMessageDialog (null, "File saved successfully.");
                else
                    JOptionPane.showMessageDialog (null, "File could not be saved!");
        // Create the GUI and show it. For thread safety,
        // this method should be invoked from the
        // event-dispatching thread.
        private static void createAndShowGUI ()
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated (true);
            //Create and set up the window.
            JFrame frame = new JFrame ("Swisha Computer House");
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new CPT ();
            newContentPane.setOpaque (true); //content panes must be opaque
            frame.setContentPane (newContentPane);
            //Display the window.
            frame.pack ();
            frame.setSize (300, 300);
            frame.setVisible (true);
        public static void main (String[] args)
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater (new Runnable ()
                public void run ()
                    createAndShowGUI ();
    }Hey, and if anyone knows how to get the first column's numbers from the file to show up in descending order (1 through to, say, 500), please let me know.
    Thank you for any help.

    It looks to me as if this layout is treating it with the same dimensions as the buttons'.Thats the way a GridLayout works.
    Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use Layout Managers. You can mix an match individual Layout Managers to get the effect desired.
    I would suggest you need to change your design. Your code for continually removing and adding components is not the best design. You should probably have a panel with all your buttons. Then you would have different panels for each of your sub functions. The display of these panels would be controlled by a Card Layout. The tutorial has working examples of this.
    You can't use a Properties file to save data from the table (at least not the way you are attempting to use it). I gave you a solution in your last posting.

  • JTable insertRow Problem

    Hello,
    I have the following code:
    I have this method in my model class which extends abstract table model
    public boolean add(int row)
    if ( row < 0 )
    return false;
    m_macDataVector.insertElementAt( new LogonData( pane.mDescription() , "", "", pane.mSysNo(),
    pane.mApp(), pane.mRtr()), row);
    return true;
    In another class I have this code
    int row = pad.getSelRow();
    if( pad.LogonModel.add(row+1));
    pad.TbLogon.tableChanged(new TableModelEvent(pad.sapLogonModel, row+1, row+1, TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT));
    pad.TbLogon.repaint();
    public String mDescription()
    return description.getText();
    public String mSysNo()
    return sysno.getText();
    public String mAppServer()
    return appsrv.getText();
    public String mRtr()
    return rtr.getText();
    Though I am able to insert the new element into the vector I am not able to show it in the table view. I have checked in the debugging mode and the new data is in the vector but I am not able to insert the new row in the JTable. Is it because that I am using two different classes or....
    Any body has any ideas?
    Thanks in advance.
    Reg,
    sk

    hi
    try if this helps
    eg.
    declare this following in constructor....
    Object [] columnNames = {"Select","Sr No",
                   "Roll No",
                   "Dept",
                   "Item",
                   "Quality",
                   "Challan Quantity",
                   "Actual",
                   " Reason ",
                   "Goods Faulty",
                   "Detailid"
    Mytablemodel customModel = new Mytablemodel(columnNames, 0);
    jTable1 = new JTable(customModel);
    then this is the inner class
    class Mytablemodel extends DefaultTableModel
         public Mytablemodel(Object[][] data, Object[] columnNames)
         super(data,columnNames);
         System.out.println("New Constructor Called");
         public Mytablemodel(Object[] columnNames, int row)
         super(columnNames, row);
         System.out.println("New1 Constructor Called");
         public void deleteRow(int row)
              removeRow(row);
         public void addNewRow()
         Object[] data = {new Boolean(false),new Integer(getRowCount() + 1),"","","","","",new Double(0),"",new Double(0),""};
         addRow(data);
         public int getColumnCount(Object[] columnNames)
              return columnNames.length;
         public Class getColumnClass(int c)
              return getValueAt(0, c).getClass();
    }// end of custommodel class
    then just use the methods declared in the class
    eg.
    customModel.addNewRow();
    hope this helps u.......
    Praveena

  • Entire JDBC communication stopped if problem with one single JDBC interface

    Hello,
    Will the entire JDBC communication stopped if problem with one single JDBC interface?
    Thanks,
    Soorya.

    hi surya,
    this will happend if u use maintain order at runtime at interface determination.
    just uncheck this option if u dont neet EOIO.
    if you are getting the problem if u r going for EO then the problem might be using same JDBC channel for all interfaces.
    if each interface is expected with a high load then it better to go for dedicated channels for interfaces.
    like INTERFACE A should use JDBC A channel and INTERFACE B should use JDBC B channel.
    Thanks & Regards,
    Rama krishna

  • JDBC communication stopped if problem with one single JDBC interface

    Hello,
    Can you please explain this phrase
    "JDBC communication stopped if problem with one single JDBC interface"
    THanks,
    Soorya

    If you are having a problem with a JDBC interface (lets consider this to be a communication channel) then the communication is stopped (via that channel) (only in the case of EOIO).
    Hope this clarifies.
    Cheers,
    Sarath
    Award if helpful.

  • Update JTable model col through header name in fast way

    old day, i update my JTable model through the way :
    tableModel.setValueAt(aValue, rowIndex, jTable1.getColumn("HeaderName").getModelIndex());now, i am adding a feature to my table, where the user can remove column.
    when user remove the column, is just the JTable GUI column being removed,. the underlining TableModel column is still there.
    my new feature will broke my above code.
    hence, i change my code to :
    for(columnIndex=0; columnIndex<columnCount; columnIndex++) {
         String name = tableModel.getColumnName(columnIndex)
         if(name.equals("HeaderName"))
              tableModel.setValueAt(aValue, rowIndex, columnIndex)
    }instead of looping through, is there any way i can retrieve the column model index in a fast way?
    a way i can think off, is inherit from DefaultTableModel, and add a map member, so that it can directly map the header name to col index.
    is there any better way?
    thanks

    i don't know why but the KeyListener does work fine with another application that i have also created Not a good solution. First of all the column still exists, so the user will tab from one column to your "hidden" column and wonder whats happening.
    The correct solution is to remove the TableColumn from the TableColumnModel. You can still access the data in the TableModel:
    table.getModel().getValueAt(...)
    No need to use the convertColumnIndexToModel.

  • JTable , TableModelListener problem

    Hi,
    I have a question about using the JTable with a TableModelListener.It might be a very silly question for some but .. Jtable I still haven't got it right ..always get confused
    I have TableModelListener for my Jtable Model .. I want the listener to be called only when the
    data in the editable cell changes .. as per now .. each time I tab through the table cells without even changing the data in the cell .
    Can someone help me how this can be done .. so that the control goes into the listener only when the data in the cell has been changed .
    One more issuse is that .. the listener is called more than once ..
    I have added a addListSelectionListener for the same JTable and each time a particular row in the table
    is selected .. it called more than once
    Can some one help me with this one please
    thanks
    sandsouza

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class TableProcessing extends JFrame implements TableModelListener
        JTable table;
        public TableProcessing()
            String[] columnNames = {"Item", "Quantity", "Price", "Cost"};
            Object[][] data =
                {"Bread", new Integer(1), new Double(1.11), new Double(1.11)},
                {"Milk", new Integer(1), new Double(2.22), new Double(2.22)},
                {"Tea", new Integer(1), new Double(3.33), new Double(3.33)},
                {"Cofee", new Integer(1), new Double(4.44), new Double(4.44)}
            DefaultTableModel model = new DefaultTableModel(data, columnNames);
            model.addTableModelListener( this );
            table = new JTable( model )
                //  Returning the Class of each column will allow different
                //  renderers to be used based on Class
                public Class getColumnClass(int column)
                    return getValueAt(0, column).getClass();
                //  The Cost is not editable
                public boolean isCellEditable(int row, int column)
                     int modelColumn = convertColumnIndexToModel( column );
                    return (modelColumn == 3) ? false : true;
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
         *  The cost is recalculated whenever the quantity or price is changed
        public void tableChanged(TableModelEvent e)
            if (e.getType() == TableModelEvent.UPDATE)
                int row = e.getFirstRow();
                int column = e.getColumn();
                System.out.println(row + " : " + column);
                if (column == 1 || column == 2)
                    int    quantity = ((Integer)table.getModel().getValueAt(row, 1)).intValue();
                    double price = ((Double)table.getModel().getValueAt(row, 2)).doubleValue();
                    Double value = new Double(quantity * price);
                    table.getModel().setValueAt(value, row, 3);
        public static void main(String[] args)
            TableProcessing frame = new TableProcessing();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }

  • JTable Model   --  How to set the width of columns

    Hello,
    This project of mine is due in 2 days. :(
    I am using AbstractTableModel and I can't figure out how to set the columns' width inside my JTable?
    This following code does not work.
    int vColIndex = 1;
    TableColumn col = table.getColumnModel().getColumn(vColIndex);
    int width=399;
    col.setPreferredWidth(width);Please remember, that I'm using AbstractTableModel and not just simple JTables.
    Thanks in advance.

    The DataModel (AbstractTableModel or otherwise) has nothing to do with the table column size. The DataModel is used to store data.
    When you create a JTable using a DataModel then a TableColumn is created for each column in the DataModel using a default column size. The normal order of creation would be:
    TableModel model = new DefaultTableModel(...);
    JTable table = new JTable(model);
    Now that the table and table columns are created you can change the size of the columns:
    int vColIndex = 1;
    TableColumn col = table.getColumnModel().getColumn(vColIndex);
    int width=399;
    col.setPreferredWidth(width);
    So your code looks ok.
    However, if somewhere in you code you do:
    a) table.setModel(...)
    b) fireTableStructureChanged();
    then the table columns are recreated based on the current DataModel and the table column size would be reset to the default values.

  • How can I add rows to a JTable based on an Abstract Table Model?

    I have done this ...
    public class myui extends JPanel {
    private AbstractTableModel jTable1Model;
    blah blah
            jTable1Model = new AbstractTableModel() {
                 String[] column = new String[]{"TID", "Name", "Address"};
                 Vector<Vector<Object>> table = new Vector<Vector<Object>>();
                 @Override
                 public int getRowCount() {
                      return table.size();
                 @Override
                 public int getColumnCount() {
                      return column.length;
                 @Override
                 public String getColumnName(int col) {
                      return column[col];
                 @Override
                 public Object getValueAt(int row, int column) {
                      return table.get(row).get(column);
                 @Override
                 public void setValueAt(Object value, int row, int column) {
                      table.get(row).set(column, value);
                      fireTableCellUpdated(row, column);
                 public void insertRow() {
                      Vector<Object> columns = new Vector<Object>();
                      columns.add(null);columns.add(null);columns.add(null);
                      table.add(columns);
                      fireTableRowsInserted(0, table.size());
    blah blah
        public synchronized void ImportVisitorDataToJTable1(Object value, int row, int col) {
            jTable1Model.InsertRow();  <-----///// This line not being recognised as a valid member function call
           jTable1.setValueAt(value, row, col);
    }I thought to insert a row I can define a function in the abstracttablemodel class and then instantiate the class and override or create new methods that I can use.
    But after instantiating the class and overriding appropriately and adding the insertRow function, when I try to use it in ImportVisitorDataToJTable1 as seen above its not being recognized as a funtion of jTable1Model

    1. respect naming conventions. Example: myui --> MyUI, ImportVisitorDataToJTable1 -->importVisitorDataToJTable1
    2. convert Anonymous to Member: AbstractTableModel --> MyTableModel
    3. row parameter makes no sense here as it depends on current row count:
        public synchronized void importVisitorDataToJTable1(Object value, int col) {
            int row = jTable1Model.getRowCount();4. here is a more adequate "fireTable.."-call for insertRow:
    fireTableRowsInserted(table.size() - 1, table.size() - 1);
    5. check if you can take advantage using DefaultTableModel as suggested by Maxideon.

  • JTable not seeing Column names from Abstract table model

    Here is the code for the getColumnNames method
    It is getting called and it is send the correct data However the Headings do not match the data.
    public String getColumnName(int col){
    String s_retval;
    switch (m_iMode){
    case PhoneTableModel.NORMALVIEW:
    default:
    s_retval= m_sHeadingsDefault[col];
    break;
    System.err.println("TableNames "+s_retval);
    return s_retval;
    }

    Why do you show the part of the code that works?!
    Show how you create and display your table!
    What is displayed in the headings then?
    Which JDK on which platform?

  • Jtable Update problem .. Please help !!!!!!!!

    Hi ,
    I am trying to get my updated Jtable, stored in a table of database over a previous table ......after updating it via drag n drop ....
    But even after I change the cell position to make the changes ... it still takes up the old value of that cell and not the new one while writing the data in the database table...
    Here is the code .... Please see it and tell me if it is possible :
    package newpackage;
    import java.sql.*;
    import java.util.Vector;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Dimension;
    import java.text.*;
    import newpackage.ExcelExporter;
    import java.awt.Dimension;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    import java.awt.print.*;
    import java.awt.*;
    import java.io.*;
    import java.util.Random.*;
    import javax.swing.*;
    import java.text.*;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableColumn;
    public class tab7le extends javax.swing.JFrame {
        Vector columnNames = new Vector();
        Vector data = new Vector();
        Connection con;
    Statement stat;
    ResultSet rs;
    int li_cols = 0;
    Vector allRows;
    Vector row;
    Vector newRow;
    Vector colNames;
    String dbColNames[];
    String pkValues[];
    String tableName;
    ResultSetMetaData myM;
    String pKeyCol;
    Vector deletedKeys;
    Vector newRows;
    boolean ibRowNew = false;
    boolean ibRowInserted = false;
        private Map<String, Color> colormap = new HashMap<String, Color>();
        /** Creates new form tab7le */
        public tab7le() {
            populate();
            initComponents();
           public void updateDB(){
                     try{
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          catch (ClassNotFoundException e){
                System.out.println("Cannot Load Driver!");
          try{
             String url = "jdbc:odbc:FAMS";
             con = DriverManager.getConnection(url);
             stat = con.createStatement();
             rs = stat.executeQuery("Select * from SubAllot");
             deletedKeys = new Vector();
             newRows = new Vector();
             myM = rs.getMetaData();
             tableName = myM.getTableName(1);
             li_cols = myM.getColumnCount();
             dbColNames = new String[li_cols];
             for(int col = 0; col < li_cols; col ++){
                dbColNames[col] = myM.getColumnName(col + 1);
             allRows = new Vector();
             while(rs.next()){
                newRow = new Vector();
                for(int i = 1; i <= li_cols; i++){
                   newRow.addElement(rs.getObject(i));
                } // for
                allRows.addElement(newRow);
             } // while
          catch(SQLException e){
             System.out.println(e.getMessage());
    String updateLine[] = new String[dbColNames.length];
          try{
             DatabaseMetaData dbData = con.getMetaData();
             String catalog;
             // Get the name of all of the columns for this table
             String curCol;
             colNames = new Vector();
             ResultSet rset1 = dbData.getColumns(null,null,tableName,null);
             while (rset1.next()) {
                curCol = rset1.getString(4);
                colNames.addElement(curCol);
             rset1.close();
             pKeyCol = colNames.firstElement().toString();
             // Go through the rows and perform INSERTS/UPDATES/DELETES
             int totalrows;
             totalrows = allRows.size();
             String dbValues[];
             Vector currentRow = new Vector();
             pkValues = new String[allRows.size()];
             // Get column names and values
             for(int i=0;i < totalrows;i++){
                currentRow = (Vector) allRows.elementAt(i);
                int numElements = currentRow.size();
                dbValues = new String[numElements];
                for(int x = 0; x < numElements; x++){
                   String classType = currentRow.elementAt(x).getClass().toString();
                   int pos = classType.indexOf("String");
                   if(pos > 0){ // we have a String
                      dbValues[x] = "'" + currentRow.elementAt(x) + "'";
                      updateLine[x] = dbColNames[x] + " = " + "'" + currentRow.elementAt(x) + "',";
                      if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
                        pkValues[i] = currentRow.elementAt(x).toString() ;
                   pos = classType.indexOf("Integer");
                   if(pos > 0){ // we have an Integer
                      dbValues[x] = currentRow.elementAt(x).toString();
                      if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
                         pkValues[i] = currentRow.elementAt(x).toString();
                      else{
                         updateLine[x] = dbColNames[x] + " = " + currentRow.elementAt(x).toString() + ",";
                   pos = classType.indexOf("Boolean");
                   if(pos > 0){ // we have a Boolean
                      dbValues[x] = currentRow.elementAt(x).toString();
                      updateLine[x] = dbColNames[x] + " = " + currentRow.elementAt(x).toString() + ",";
                      if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
                         pkValues[i] = currentRow.elementAt(x).toString() ;
                } // For Loop
                // If we are here, we have read one entire row of data. Do an UPDATE or an INSERT
                int numNewRows = newRows.size();
                int insertRow = 0;
                boolean newRowFound;
                for (int z = 0;z < numNewRows;z++){
                   insertRow = ((Integer) newRows.get(z)).intValue();
                   if(insertRow == i+1){
                      StringBuffer InsertSQL = new StringBuffer();
                      InsertSQL.append("INSERT INTO " + tableName + " (");
                      for(int zz=0;zz<=dbColNames.length-1;zz++){
                         if (dbColNames[zz] != null){
                            InsertSQL.append(dbColNames[zz] + ",");
                      // Strip out last comma
                      InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");
                      InsertSQL.append(" VALUES(" + pkValues[i] + ",");
                      for(int c=1;c < dbValues.length;c++){
                         InsertSQL.append(dbValues[c] + ",");
                      InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");
                      System.out.println(InsertSQL.toString());
                      stat.executeUpdate(InsertSQL.toString());
                      ibRowInserted=true;
                } // End of INSERT Logic
                // If row has not been INSERTED perform an UPDATE
                if(ibRowInserted == false){
                   StringBuffer updateSQL = new StringBuffer();
                   updateSQL.append("UPDATE " + tableName + " SET ");
                   for(int z=0;z<=updateLine.length-1;z++){
                      if (updateLine[z] != null){
                         updateSQL.append(updateLine[z]);
                   // Replace the last ',' in the SQL statement with a blank. Then add WHERE clause
                   updateSQL.replace(updateSQL.length()-1,updateSQL.length()," ");
                   updateSQL.append(" WHERE " + pKeyCol + " = " + pkValues[i] );
                   System.out.println(updateSQL.toString());
                   stat.executeUpdate(updateSQL.toString());
                   } //for
             catch(Exception ex){
                System.out.println("SQL Error! Cannot perform SQL UPDATE " + ex.getMessage());
             // Delete records from the DB
             try{
                int numDeletes = deletedKeys.size();
                String deleteSQL;
                for(int i = 0; i < numDeletes;i++){
                   deleteSQL = "DELETE FROM " + tableName + " WHERE " + pKeyCol + " = " +
                                                ((Integer) deletedKeys.get(i)).toString();
                System.out.println(deleteSQL);
                   stat.executeUpdate(deleteSQL);
                // Assume deletes where successful. Recreate Vector holding PK Keys
                deletedKeys = new Vector();
             catch(Exception ex){
                System.out.println(ex.getMessage());
        public void populate()
            try
                //  Connect to the Database
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                Connection con = DriverManager.getConnection("Jdbc:Odbc:FAMS"," "," ");
                System.out.println("ok1");
                //  Read data from a table
                String sql;
                 sql = "Select * from SubAllot";
                 System.out.println("ok1");
                Statement stmt = con.createStatement();
                System.out.println("ok1");
                ResultSet rs = stmt.executeQuery( sql );
                System.out.println("ok1");
                ResultSetMetaData md = rs.getMetaData();
                System.out.println("ok1");
                int columns = md.getColumnCount();
                for(int i = 0;i<columns;i++){
                    columnNames.addElement(md.getColumnName(i+1));
                    System.out.println("ok2");
                while (rs.next())
                    Vector row = new Vector(columns);
                    for (int i = 1; i <columns+1; i++)
                        row.addElement( rs.getObject(i) );
                    data.addElement( row );
            catch(Exception e){
                e.printStackTrace();
                 public void dropmenu(JTable table,TableColumn subpref1) {
            //Set up the editor for the sport cells.
            JComboBox comboBox = new JComboBox();
          for (int i = 0;i<=20;i++)
           comboBox.addItem(i);
            subpref1.setCellEditor(new DefaultCellEditor(comboBox));
            //Set up tool tips for the sport cells.
            DefaultTableCellRenderer renderer =
                    new DefaultTableCellRenderer();
            renderer.setToolTipText("Click for combo box");
            subpref1.setCellRenderer(renderer);
                       abstract class StringTransferHandler extends TransferHandler {
            public int dropAction;
            protected abstract String exportString(final JComponent c);
            protected abstract void importString(final JComponent c, final String str);
            @Override
            protected Transferable createTransferable(final JComponent c) {
                return new StringSelection(exportString(c));
            @Override
            public int getSourceActions(final JComponent c) {
                return MOVE;
            @Override
            public boolean importData(final JComponent c, final Transferable t) {
                if (canImport(c, t.getTransferDataFlavors())) {
                    try {
                        String str = (String) t.getTransferData(DataFlavor.stringFlavor);
                        importString(c, str);
                        return true;
                    } catch (UnsupportedFlavorException ufe) {
                    } catch (IOException ioe) {
                return false;
            @Override
            public boolean canImport(final JComponent c, final DataFlavor[] flavors) {
                for (int ndx = 0; ndx < flavors.length; ndx++) {
                    if (DataFlavor.stringFlavor.equals(flavors[ndx])) {
                        return true;
                return false;
        class TableTransferHandler extends StringTransferHandler {
            private int dragRow;
            private int[] dragColumns;
            private BufferedImage[] image;
            private int row;
            private int[] columns;
            public JTable target;
            private Map<String, Color> colormap;
            private TableTransferHandler(final Map<String, Color> colormap) {
                this.colormap = colormap;
            @Override
            protected Transferable createTransferable(final JComponent c) {
                JTable table = (JTable) c;
                dragRow = table.getSelectedRow();
                dragColumns = table.getSelectedColumns();
                createDragImage(table);
                return new StringSelection(exportString(c));
            protected String exportString(final JComponent c) {
                JTable table = (JTable) c;
                row = table.getSelectedRow();
                columns = table.getSelectedColumns();
                StringBuffer buff = new StringBuffer();
                colormap.clear();
                for (int j = 0; j < columns.length; j++) {
                    Object val = table.getValueAt(row, columns[j]);
                    buff.append(val == null ? "" : val.toString());
                    if (j != columns.length - 1) {
                        buff.append(",");
                    colormap.put(row+","+columns[j], Color.LIGHT_GRAY);
                table.repaint();
                return buff.toString();
            protected void importString(final JComponent c, final String str) {
                target = (JTable) c;
                DefaultTableModel model = (DefaultTableModel) target.getModel();
                String[] values = str.split("\n");
                int colCount = target.getSelectedColumn();
                int max = target.getColumnCount();
                for (int ndx = 0; ndx < values.length; ndx++) {
                    String[] data = values[ndx].split(",");
                    for (int i = 0; i < data.length; i++) {
                        String string = data;
    if(colCount < max){
    Object val = model.getValueAt(target.getSelectedRow(), colCount);
    model.setValueAt(string, target.getSelectedRow(), colCount);
    model.setValueAt(val, dragRow, dragColumns[i]);
    colCount++;
    public BufferedImage[] getDragImage() {
    return image;
    private void createDragImage(final JTable table) {
    if (dragColumns != null) {
    try {
    image = new BufferedImage[dragColumns.length];
    for (int i = 0; i < dragColumns.length; i++) {
    Rectangle cellBounds = table.getCellRect(dragRow, i, true);
    TableCellRenderer r = table.getCellRenderer(dragRow, i);
    DefaultTableModel m = (DefaultTableModel) table.getModel();
    JComponent lbl = (JComponent) r.getTableCellRendererComponent(table,
    table.getValueAt(dragRow, dragColumns[i]), false, false, dragRow, i);
    lbl.setBounds(cellBounds);
    BufferedImage img = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
    BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics2D graphics = img.createGraphics();
    graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));
    lbl.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
    lbl.paint(graphics);
    graphics.dispose();
    image[i] = img;
    } catch (RuntimeException re) {
    class TableDropTarget extends DropTarget {
    private Insets autoscrollInsets = new Insets(20, 20, 20, 20);
    private Rectangle rect2D = new Rectangle();
    private TableTransferHandler handler;
    public TableDropTarget(final TableTransferHandler h) {
    super();
    this.handler = h;
    @Override
    public void dragOver(final DropTargetDragEvent dtde) {
    handler.dropAction = dtde.getDropAction();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    Point location = dtde.getLocation();
    int row = table.rowAtPoint(location);
    int column = table.columnAtPoint(location);
    table.changeSelection(row, column, false, false);
    paintImage(table, location);
    autoscroll(table, location);
    super.dragOver(dtde);
    public void dragExit(final DropTargetDragEvent dtde) {
    clearImage((JTable) dtde.getDropTargetContext().getComponent());
    super.dragExit(dtde);
    @Override
    public void drop(final DropTargetDropEvent dtde) {
    Transferable data = dtde.getTransferable();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    clearImage(table);
    handler.importData(table, data);
    super.drop(dtde);
    private final void paintImage(final JTable table, final Point location) {
    Point pt = new Point(location);
    BufferedImage[] image = handler.getDragImage();
    if (image != null) {
    table.paintImmediately(rect2D.getBounds());
    rect2D.setLocation(pt.x - 15, pt.y - 15);
    int wRect2D = 0;
    int hRect2D = 0;
    for (int i = 0; i < image.length; i++) {
    table.getGraphics().drawImage(image[i], pt.x - 15, pt.y - 15, table);
    pt.x += image[i].getWidth();
    if (hRect2D < image[i].getHeight()) {
    hRect2D = image[i].getHeight();
    wRect2D += image[i].getWidth();
    rect2D.setSize(wRect2D, hRect2D);
    private final void clearImage(final JTable table) {
    table.paintImmediately(rect2D.getBounds());
    private Insets getAutoscrollInsets() {
    return autoscrollInsets;
    private void autoscroll(final JTable table, final Point cursorLocation) {
    Insets insets = getAutoscrollInsets();
    Rectangle outer = table.getVisibleRect();
    Rectangle inner = new Rectangle(outer.x + insets.left,
    outer.y + insets.top,
    outer.width - (insets.left + insets.right),
    outer.height - (insets.top + insets.bottom));
    if (!inner.contains(cursorLocation)) {
    Rectangle scrollRect = new Rectangle(cursorLocation.x - insets.left,
    cursorLocation.y - insets.top,
    insets.left + insets.right,
    insets.top + insets.bottom);
    table.scrollRectToVisible(scrollRect);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    table = new javax.swing.JTable();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    table.setModel(new javax.swing.table.DefaultTableModel(
    data, columnNames
    jScrollPane1.setViewportView(table);
    //populate();
    table.getTableHeader().setReorderingAllowed(false);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setCellSelectionEnabled(true);
    table.setDragEnabled(true);
    TableTransferHandler th = new TableTransferHandler(colormap);
    table.setTransferHandler(th);
    table.setDropTarget(new TableDropTarget(th));
    dropmenu(table, table.getColumnModel().getColumn(11));
    jButton1.setText("Update");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    jButton2.setText("Ex");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(92, 92, 92)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 605, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(layout.createSequentialGroup()
    .addGap(347, 347, 347)
    .addComponent(jButton1)
    .addGap(115, 115, 115)
    .addComponent(jButton2)))
    .addContainerGap(73, Short.MAX_VALUE))
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(47, 47, 47)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(58, 58, 58)
    .addComponent(jButton1)
    .addContainerGap(83, Short.MAX_VALUE))
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton2)
    .addGap(65, 65, 65))))
    pack();
    }// </editor-fold>
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    updateDB(); // TODO add your handling code here:
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    try {
    String pathToDesktop = System.getProperty("user.home")+File.separator+"Desktop";
    pathToDesktop = pathToDesktop + "//Final Allotment.xls";
    ExcelExporter exp = new ExcelExporter();
    exp.exportTable(table, new File(pathToDesktop));
    JOptionPane.showMessageDialog(this,"File exported and saved on desktop!");
    catch (IOException ex) {
    System.out.println(ex.getMessage());
    ex.printStackTrace();
    } // TODO add your handling code here:
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new tab7le().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table;
    // End of variables declaration
    Please help !!!!!!!!
    Thanks in advance.....                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                

    Here is the code Do you expect people to read through 400 lines of code to understand what you are doing?
    Why post code with access to a database? We can't access the database.
    Search the forum for my "Database Information" (without the space) example class which shows you how to refresh a table with new data.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.

  • JTable printing problem

    Hi , I have a problem add printing routine for printing to this code.
    Sombody help me.
    I no post all code but my prube no functioned.
    thanks you
    code :
    package com.froses.tablemodels;
    * SimpleDBTable.java
    * A demonstration of using ODBC to read data from an Access database
    * and display the values in a JTable.
    * This file requires that the new.mdb file exists and has been mapped
    * using ODBC to a datastore named 'newdb' with blank username and password.
    * Gordon Branson January 2004
    import javax.swing.*;
    import java.awt.Dimension;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    public class SimpleDBTable extends JPanel {
    private boolean DEBUG = true;
    private int rows = 10, cols = 5;
    private String url = "jdbc:odbc:Sego";
    private Connection con;
    private Statement stmt;
    private JButton btnRead, btnDelete, btnWrite, btnClose;
              /* Setup the table column names */
    private String[] columnNames = {"Medico",
    "Descripci�n",
    "Obra social",
    "Items",
    "Codigo"};
              /* declare an Object array large enough to hold the database table */
    private Object[][] data = new Object[rows][cols];
    private JTable table;
    public SimpleDBTable() {
    super(new BorderLayout());
    /* Load ODBC diver */
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    } catch(java.lang.ClassNotFoundException e) {
    System.err.print("ClassNotFoundException: ");
    System.err.println(e.getMessage());
              /* create the JTable */
    table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 300));
    /* Now read from the database */
    populateTable();
    if (DEBUG) {
    table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    printDebugData();
    //Create the Title Label.
    JLabel title = new JLabel("Database Access in Java");
    title.setFont(new java.awt.Font("Arial", 1, 24));
    title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    //Add the label to this panel.
    add("North",title);
    //Create the scroll pane and add the JTable to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this panel.
    add("Center",scrollPane);
    // Create a button panel with a default layout
    JPanel buttons = new JPanel();
    // Create the buttons
    btnRead = new JButton("Read");
    btnClose = new JButton("Close");
    btnWrite = new JButton("Write");
    btnDelete = new JButton("Delete");
    // Add action listeners
    btnRead.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    populateTable();
    btnDelete.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    deleteTable();
    btnWrite.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    writeTable();
    btnClose.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    System.exit(0);
    // Add the buttons to the button panel
    buttons.add(btnRead);
    buttons.add(btnWrite);
    buttons.add(btnDelete);
    buttons.add(btnClose);
    // Add the buttons panel to main panel
    add("South",buttons);
    private void populateTable(){
         /* Define the SQL Query to get all data from the database table */
    String query = "SELECT * FROM Datos";
    /* First clear the JTable */
    clearTable();
    /* get a handle for the JTable */
    javax.swing.table.TableModel model = table.getModel();
    int r = 0;
    try {
    /* connect to the database */
    con = DriverManager.getConnection(url, "", "");
    stmt = con.createStatement();
    /* run the Query getting the results into rs */
                   ResultSet rs = stmt.executeQuery(query);
                   while ((rs.next()) && (r<rows)) {
                        /* for each row get the fields
                        note the use of Object - necessary
                        to put the values into the JTable */
                   Object nm = rs.getObject("Medico_solic");
                   Object sup = rs.getObject("Descip_Item");
                   Object pri = rs.getObject("Obra_Social");
                   Object sal = rs.getObject("M�dico_opera");
                   Object tot = rs.getObject("Codigo_estudio");
                   model.setValueAt(nm, r, 0);
                   model.setValueAt(sup, r, 1);
                   model.setValueAt(pri, r, 2);
                   model.setValueAt(sal, r, 3);
                   model.setValueAt(tot, r, 4);
                   r++;
    stmt.close();
    con.close();
    } catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    private void deleteTable(){
         emptyTable();
         clearTable();
    private void emptyTable(){
         /* Define the SQL Query to get all data from the database table */
    String query = "DELETE * FROM COFFEES";
    try {
    /* connect to the database */
    con = DriverManager.getConnection(url, "", "");
    stmt = con.createStatement();
    /* run the Query */
                   stmt.executeUpdate(query);
    stmt.close();
    con.close();
    } catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    /* private void writeTable(){
         /* First clear the table */
    /*      emptyTable();
         PreparedStatement insertRow;// = con.prepareStatement(
         String insertString = "INSERT INTO COFFEES " +
                                  "VALUES (?, ?, ?, ?, ?)";
    int numRows = table.getRowCount();
    javax.swing.table.TableModel model = table.getModel();
    Integer sup, sal, tot;
    Double pri;
    Object o;
    if(DEBUG) System.out.println("\nDoing Write...");
    try {
    /* connect to the database */
    /* con = DriverManager.getConnection(url, "", "");
    insertRow = con.prepareStatement(insertString);
         for (int r=0; r < numRows; r++) {
              if (model.getValueAt(r, 0) != null){
                   insertRow.setString(1, (String) model.getValueAt(r, 0));
                   //o = model.getValueAt(r, 1);
                   if(DEBUG) System.out.println(model.getValueAt(r, 1).toString());
                   sup = new Integer((String) model.getValueAt(r, 1));
                   insertRow.setInt(2, sup.intValue());
                   pri = new Double((String) model.getValueAt(r, 2));
                   insertRow.setDouble(3, pri.doubleValue());
                   sal = new Integer((String) model.getValueAt(r, 3));
                   insertRow.setInt(4, sal.intValue());
                   tot = new Integer((String) model.getValueAt(r, 4));
                   insertRow.setInt(5, tot.intValue());
                   insertRow.executeUpdate();
                   System.out.println("Writing Row " + r);
    insertRow.close();
    con.close();
    } catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    clearTable();
    private void writeTable(){
         /* First clear the table */
         emptyTable();
         Statement insertRow;// = con.prepareStatement(
         String baseString = "INSERT INTO Datos " +
                                  "VALUES ('";
         String insertString;
    int numRows = table.getRowCount();
    javax.swing.table.TableModel model = table.getModel();
    Integer sup, sal, tot;
    Double pri;
    Object o;
    if(DEBUG) System.out.println("\nDoing Write...");
    try {
    /* connect to the database */
    con = DriverManager.getConnection(url, "", "");
         for (int r=0; r < numRows; r++) {
              if (model.getValueAt(r, 0) != null){
                   insertString = baseString + model.getValueAt(r, 0)+"',";
                   insertString = insertString + model.getValueAt(r, 1)+",";
                   insertString = insertString + model.getValueAt(r, 2)+",";
                   insertString = insertString + model.getValueAt(r, 3)+",";
                   insertString = insertString + model.getValueAt(r, 4)+");";
                   if(DEBUG) System.out.println(insertString);
              insertRow = con.createStatement();
                   insertRow.executeUpdate(insertString);
                   System.out.println("Writing Row " + r);
    insertRow.close();
    con.close();
    } catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    clearTable();
    private void clearTable(){
    int numRows = table.getRowCount();
    int numCols = table.getColumnCount();
    javax.swing.table.TableModel model = table.getModel();
    for (int i=0; i < numRows; i++) {
    for (int j=0; j < numCols; j++) {
    model.setValueAt(null, i, j);
    private void printDebugData() {
    int numRows = table.getRowCount();
    int numCols = table.getColumnCount();
    javax.swing.table.TableModel model = table.getModel();
    System.out.println("Value of data: ");
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + model.getValueAt(i, j));
    System.out.println();
    System.out.println("--------------------------");
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("SimpleDBTable");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    SimpleDBTable newContentPane = new SimpleDBTable();
    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.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    }

    http://forum.java.sun.com/thread.jspa?threadID=626207

  • JTable sorting - problem when adding elements (complete code inside)

    I�m writing this email with reference to a recent posting here but this time with the code example. (I apologize for the duplicated posting � this time it will be with the code)
    Problem: when adding more elements to the JTable (sorted) the exception: ArrayIndexOutOfBoundsException is thrown.
    Example: If the elements in the table are 10 and then the user requests for 8 � the table will produce the correct result. However, if the user will ask for 11 items (>10) the exception will be thrown.
    The program: The program below (compiles and running). A JTable is constructed with 3 items, when you click the button - the return result should be 4 items - this will generate the error, WHY?
    I would highly appreciate your thoughts why this is happening and most importantly � how to fix it.
    Thanks a lot
    3 files:
    (1) TableSorterDemo
    (2) Traveler
    (3)TableSorter
    //TableSorterDemo:
    package sorter;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    * TableSorterDemo is like TableDemo, except that it
    * inserts a custom model -- a sorter -- between the table
    * and its data model.  It also has column tool tips.
    public class TableSorterDemo implements ActionListener
         private JPanel superPanel;
         private JButton clickMe = new JButton("click me to get diff data");
         private boolean DEBUG = false;
         private DefaultListModel defaultListModel;
         private JTable table;
        public TableSorterDemo()
             superPanel = new JPanel(new BorderLayout());
             defaultListModel = new DefaultListModel();
             init1();
            TableSorter sorter = new TableSorter(new MyTableModel(defaultListModel)); //ADDED THIS     
            table = new JTable(sorter);             //NEW
            sorter.setTableHeader(table.getTableHeader()); //ADDED THIS
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            //Set up tool tips for column headers.
            table.getTableHeader().setToolTipText(
                    "Click to specify sorting; Control-Click to specify secondary sorting");
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            superPanel.add("Center", scrollPane);
            superPanel.add("South",clickMe);
            clickMe.addActionListener(this);              
        public JPanel getPanel()
             return superPanel;
        public void init1()
             //in real life this will be done from the db
             Traveler a = new Traveler();
             Traveler b = new Traveler();
             Traveler c = new Traveler();
             a.setFirstName("Elvis");
             a.setLastName("Presley");
             a.setSprot("Ping Pong");
             a.setNumYears(3);
             a.setVegetarian(true);
             b.setFirstName("Elton");
             b.setLastName("John");
             b.setSprot("Soccer");
             b.setNumYears(2);
             b.setVegetarian(true);
             c.setFirstName("shaquille");
             c.setLastName("oneil");
             c.setSprot("Golf");
             c.setNumYears(22);
             c.setVegetarian(true);
             defaultListModel.addElement(a);
             defaultListModel.addElement(b);
             defaultListModel.addElement(c);
        public void init2()
             //in real life this will be done from the db
             Traveler d = new Traveler();
             Traveler e = new Traveler();
             Traveler f = new Traveler();
             Traveler g = new Traveler();
             d.setFirstName("John");
             d.setLastName("Smith");
             d.setSprot("Tennis");
             d.setNumYears(32);
             d.setVegetarian(true);
             e.setFirstName("Ron");
             e.setLastName("Cohen");
             e.setSprot("Baseball");
             e.setNumYears(12);
             e.setVegetarian(true);
             f.setFirstName("Donald");
             f.setLastName("Mac Novice");
             f.setSprot("Vallyball");
             f.setNumYears(1);
             f.setVegetarian(true);
             g.setFirstName("Eithan");
             g.setLastName("Superstar");
             g.setSprot("Vallyball");
             g.setNumYears(21);
             g.setVegetarian(true);
             defaultListModel.addElement(d);
             defaultListModel.addElement(e);
             defaultListModel.addElement(f);
             defaultListModel.addElement(g);            
        class MyTableModel extends AbstractTableModel
             private DefaultListModel myModel;
             public MyTableModel(DefaultListModel m)
                  myModel=m;
            private String[] columnNames = {"First Name",
                                            "Last Name",
                                            "Sport",
                                            "# of Years",
                                            "Vegetarian"};
            public int getColumnCount()
                return columnNames.length;
            public int getRowCount()
                return myModel.size();
            public String getColumnName(int column)
                 return getNames()[column];             
             public String[] getNames()
                  String[] names = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
                  return names;
            public Object getValueAt(int row, int col)
                 return distributeObjectsInTable(row, col, (Traveler) myModel.elementAt(row));
            public Object distributeObjectsInTable(int row, int col, Traveler tr)
               switch(col)
                         case 0:
                              return tr.getFirstName();
                         case 1:
                           return tr.getLastName();
                      case 2:
                           return tr.getSprot();
                      case 3:
                           return new Integer(tr.getNumYears());
                      case 4:
                           return new Boolean (tr.isVegetarian());
                     default:
                         return "Error";
            public Class getColumnClass(int c)
                return getValueAt(0, c).getClass();
        private static void createAndShowGUI()
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("TableSorterDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            TableSorterDemo newContentPane = new TableSorterDemo();
            newContentPane.getPanel().setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane.getPanel());
            //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.
            javax.swing.SwingUtilities.invokeLater(new Runnable()                   
                public void run()
                    createAndShowGUI();
         public void actionPerformed(ActionEvent ae)
              if (ae.getSource()==clickMe)
                   defaultListModel.removeAllElements();
                   init2(); //if the size of the model was less than 2 items - the result will be ok.
                              //in other words, if you commens the last 2 rows of this method (addElement(f) & g)
                             // the result will be fine.
                   table.updateUI();          
    }//(2) Traveler
    package sorter;
    public class Traveler
         private String firstName;
         private String lastName;
         private String sprot;
         private int numYears;
         private boolean vegetarian;
         public String getFirstName()
              return firstName;
         public String getLastName()
              return lastName;
         public int getNumYears()
              return numYears;
         public String getSprot()
              return sprot;
         public boolean isVegetarian()
              return vegetarian;
         public void setFirstName(String firstName)
              this.firstName = firstName;
         public void setLastName(String lastName)
              this.lastName = lastName;
         public void setNumYears(int numYears)
              this.numYears = numYears;
         public void setSprot(String sprot)
              this.sprot = sprot;
         public void setVegetarian(boolean vegetarian)
              this.vegetarian = vegetarian;
    }//(3)TableSorter
    package sorter;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.*;
    public class TableSorter extends AbstractTableModel {
        protected TableModel tableModel;
        public static final int DESCENDING = -1;
        public static final int NOT_SORTED = 0;
        public static final int ASCENDING = 1;
        private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
        public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) o1).compareTo(o2);
        public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return o1.toString().compareTo(o2.toString());
        private Row[] viewToModel;
        private int[] modelToView;
        private JTableHeader tableHeader;
        private MouseListener mouseListener;
        private TableModelListener tableModelListener;
        private Map columnComparators = new HashMap();
        private List sortingColumns = new ArrayList();
        public TableSorter() {
            this.mouseListener = new MouseHandler();
            this.tableModelListener = new TableModelHandler();
        public TableSorter(TableModel tableModel) {
            this();
            setTableModel(tableModel);
        public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
            this();
            setTableHeader(tableHeader);
            setTableModel(tableModel);
        private void clearSortingState() {
            viewToModel = null;
            modelToView = null;
        public TableModel getTableModel() {
            return tableModel;
        public void setTableModel(TableModel tableModel) {
            if (this.tableModel != null) {
                this.tableModel.removeTableModelListener(tableModelListener);
            this.tableModel = tableModel;
            if (this.tableModel != null) {
                this.tableModel.addTableModelListener(tableModelListener);
            clearSortingState();
            fireTableStructureChanged();
        public JTableHeader getTableHeader() {
            return tableHeader;
        public void setTableHeader(JTableHeader tableHeader) {
            if (this.tableHeader != null) {
                this.tableHeader.removeMouseListener(mouseListener);
                TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
                if (defaultRenderer instanceof SortableHeaderRenderer) {
                    this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
            this.tableHeader = tableHeader;
            if (this.tableHeader != null) {
                this.tableHeader.addMouseListener(mouseListener);
                this.tableHeader.setDefaultRenderer(
                        new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
        public boolean isSorting() {
            return sortingColumns.size() != 0;
        private Directive getDirective(int column) {
            for (int i = 0; i < sortingColumns.size(); i++) {
                Directive directive = (Directive)sortingColumns.get(i);
                if (directive.column == column) {
                    return directive;
            return EMPTY_DIRECTIVE;
        public int getSortingStatus(int column) {
            return getDirective(column).direction;
        private void sortingStatusChanged() {
            clearSortingState();
            fireTableDataChanged();
            if (tableHeader != null) {
                tableHeader.repaint();
        public void setSortingStatus(int column, int status) {
            Directive directive = getDirective(column);
            if (directive != EMPTY_DIRECTIVE) {
                sortingColumns.remove(directive);
            if (status != NOT_SORTED) {
                sortingColumns.add(new Directive(column, status));
            sortingStatusChanged();
        protected Icon getHeaderRendererIcon(int column, int size) {
            Directive directive = getDirective(column);
            if (directive == EMPTY_DIRECTIVE) {
                return null;
            return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
        private void cancelSorting() {
            sortingColumns.clear();
            sortingStatusChanged();
        public void setColumnComparator(Class type, Comparator comparator) {
            if (comparator == null) {
                columnComparators.remove(type);
            } else {
                columnComparators.put(type, comparator);
        protected Comparator getComparator(int column) {
            Class columnType = tableModel.getColumnClass(column);
            Comparator comparator = (Comparator) columnComparators.get(columnType);
            if (comparator != null) {
                return comparator;
            if (Comparable.class.isAssignableFrom(columnType)) {
                return COMPARABLE_COMAPRATOR;
            return LEXICAL_COMPARATOR;
        private Row[] getViewToModel() {
            if (viewToModel == null) {
                int tableModelRowCount = tableModel.getRowCount();
                viewToModel = new Row[tableModelRowCount];
                for (int row = 0; row < tableModelRowCount; row++) {
                    viewToModel[row] = new Row(row);
                if (isSorting()) {
                    Arrays.sort(viewToModel);
            return viewToModel;
        public int modelIndex(int viewIndex)
            return getViewToModel()[viewIndex].modelIndex;
        private int[] getModelToView()
            if (modelToView == null) {
                int n = getViewToModel().length;
                modelToView = new int[n];
                for (int i = 0; i < n; i++) {
                    modelToView[modelIndex(i)] = i;
            return modelToView;
        // TableModel interface methods
        public int getRowCount() {
            return (tableModel == null) ? 0 : tableModel.getRowCount();
        public int getColumnCount() {
            return (tableModel == null) ? 0 : tableModel.getColumnCount();
        public String getColumnName(int column) {
            return tableModel.getColumnName(column);
        public Class getColumnClass(int column) {
            return tableModel.getColumnClass(column);
        public boolean isCellEditable(int row, int column) {
            return tableModel.isCellEditable(modelIndex(row), column);
        public Object getValueAt(int row, int column) {
            return tableModel.getValueAt(modelIndex(row), column);
        public void setValueAt(Object aValue, int row, int column) {
            tableModel.setValueAt(aValue, modelIndex(row), column);
        // Helper classes
        private class Row implements Comparable {
            private int modelIndex;
            public Row(int index) {
                this.modelIndex = index;
            public int compareTo(Object o) {
                int row1 = modelIndex;
                int row2 = ((Row) o).modelIndex;
                for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
                    Directive directive = (Directive) it.next();
                    int column = directive.column;
                    Object o1 = tableModel.getValueAt(row1, column);
                    Object o2 = tableModel.getValueAt(row2, column);
                    int comparison = 0;
                    // Define null less than everything, except null.
                    if (o1 == null && o2 == null) {
                        comparison = 0;
                    } else if (o1 == null) {
                        comparison = -1;
                    } else if (o2 == null) {
                        comparison = 1;
                    } else {
                        comparison = getComparator(column).compare(o1, o2);
                    if (comparison != 0) {
                        return directive.direction == DESCENDING ? -comparison : comparison;
                return 0;
        private class TableModelHandler implements TableModelListener {
            public void tableChanged(TableModelEvent e) {
                // If we're not sorting by anything, just pass the event along.            
                if (!isSorting()) {
                    clearSortingState();
                    fireTableChanged(e);
                    return;
                // If the table structure has changed, cancel the sorting; the            
                // sorting columns may have been either moved or deleted from            
                // the model.
                if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
                    cancelSorting();
                    fireTableChanged(e);
                    return;
                // We can map a cell event through to the view without widening            
                // when the following conditions apply:
                // a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
                // b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
                // c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
                // d) a reverse lookup will not trigger a sort (modelToView != null)
                // Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
                // The last check, for (modelToView != null) is to see if modelToView
                // is already allocated. If we don't do this check; sorting can become
                // a performance bottleneck for applications where cells 
                // change rapidly in different parts of the table. If cells
                // change alternately in the sorting column and then outside of            
                // it this class can end up re-sorting on alternate cell updates -
                // which can be a performance problem for large tables. The last
                // clause avoids this problem.
                int column = e.getColumn();
                if (e.getFirstRow() == e.getLastRow()
                        && column != TableModelEvent.ALL_COLUMNS
                        && getSortingStatus(column) == NOT_SORTED
                        && modelToView != null) {
                    int viewIndex = getModelToView()[e.getFirstRow()];
                    fireTableChanged(new TableModelEvent(TableSorter.this,
                                                         viewIndex, viewIndex,
                                                         column, e.getType()));
                    return;
                // Something has happened to the data that may have invalidated the row order.
                clearSortingState();
                fireTableDataChanged();
                return;
        private class MouseHandler extends MouseAdapter {
            public void mouseClicked(MouseEvent e) {
                JTableHeader h = (JTableHeader) e.getSource();
                TableColumnModel columnModel = h.getColumnModel();
                int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                int column = columnModel.getColumn(viewColumn).getModelIndex();
                if (column != -1) {
                    int status = getSortingStatus(column);
                    if (!e.isControlDown()) {
                        cancelSorting();
                    // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
                    // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
                    status = status + (e.isShiftDown() ? -1 : 1);
                    status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
                    setSortingStatus(column, status);
        private static class Arrow implements Icon {
            private boolean descending;
            private int size;
            private int priority;
            public Arrow(boolean descending, int size, int priority) {
                this.descending = descending;
                this.size = size;
                this.priority = priority;
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Color color = c == null ? Color.GRAY : c.getBackground();            
                // In a compound sort, make each succesive triangle 20%
                // smaller than the previous one.
                int dx = (int)(size/2*Math.pow(0.8, priority));
                int dy = descending ? dx : -dx;
                // Align icon (roughly) with font baseline.
                y = y + 5*size/6 + (descending ? -dy : 0);
                int shift = descending ? 1 : -1;
                g.translate(x, y);
                // Right diagonal.
                g.setColor(color.darker());
                g.drawLine(dx / 2, dy, 0, 0);
                g.drawLine(dx / 2, dy + shift, 0, shift);
                // Left diagonal.
                g.setColor(color.brighter());
                g.drawLine(dx / 2, dy, dx, 0);
                g.drawLine(dx / 2, dy + shift, dx, shift);
                // Horizontal line.
                if (descending) {
                    g.setColor(color.darker().darker());
                } else {
                    g.setColor(color.brighter().brighter());
                g.drawLine(dx, 0, 0, 0);
                g.setColor(color);
                g.translate(-x, -y);
            public int getIconWidth() {
                return size;
            public int getIconHeight() {
                return size;
        private class SortableHeaderRenderer implements TableCellRenderer {
            private TableCellRenderer tableCellRenderer;
            public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
                this.tableCellRenderer = tableCellRenderer;
            public Component getTableCellRendererComponent(JTable table,
                                                           Object value,
                                                           boolean isSelected,
                                                           boolean hasFocus,
                                                           int row,
                                                           int column) {
                Component c = tableCellRenderer.getTableCellRendererComponent(table,
                        value, isSelected, hasFocus, row, column);
                if (c instanceof JLabel) {
                    JLabel l = (JLabel) c;
                    l.setHorizontalTextPosition(JLabel.LEFT);
                    int modelColumn = table.convertColumnIndexToModel(column);
                    l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
                return c;
        private static class Directive {
            private int column;
            private int direction;
            public Directive(int column, int direction) {
                this.column = column;
                this.direction = direction;
    }

    The table listens to the TableModel for changes. Changing the table by adding/removing
    rows or columns has no affect on its table model. If you make changes to the table model
    the table will be notified by its TableModelListener and change its view. So tell
    MyTableModel about the change of data:
    public class TableSorterDemo implements ActionListener
        MyTableModel tableModel;
        public TableSorterDemo()
            defaultListModel = new DefaultListModel();
            init1();
            tableModel = new MyTableModel(defaultListModel);
            TableSorter sorter = new TableSorter(tableModel);
        public void actionPerformed(ActionEvent ae)
            if (ae.getSource()==clickMe)
                defaultListModel.removeAllElements();
                init2();
                tableModel.fireTableStructureChanged();
    }

  • Strange JTable update problems

    I am having some strange issues with a JTable.
    I have a custom AbstractTableModel that displays various properties of a list of Objects. I am using a java.util.Vector to store this list.
    The user is given several JComboBox objects which contain filters for my table, when any of these filters are changed, a class that manages my Database is asked to return a Vector full of objects that match these filters.
    I then set my table data Vector equal to this returned list and invoke fireTableStructureChanged() from my table model. This part works fine, the strange thing is, if the user has a table element selected and then they change the filters, the table will not update, it actually goes blank, but oddly enough the scroll bar on the scroll pane stays the same length as the old table.
    When I invoke the exact same update method again (which just sets the Vector containing my data to a new value, and fires the event) the table will update this time.
    I have tried calling MyJTable.getSelectionModel().clearSelection() in the hope that it will fix my problem, but it does not seem to do anything.
    So is my problem some strange event or threading glitch, or an issue with JScrollPane mabye?
    Thanks in advance for any help

    Try using the DefaultTableModel to see if you have the same problem. If not then you know the problem is with your custom TableModel.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)",
    see http://homepage1.nifty.com/algafield/sscce.html,
    that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the "Code Formatting Tags",
    see http://forum.java.sun.com/help.jspa?sec=formatting,
    so the posted code retains its original formatting.

Maybe you are looking for

  • Error message is not displayed

    Hi all, I am working on Tomcat server and JSP. i have created a web page using JSP and html. when i click on submit button, it should display the next page. if any error is there, it should display the error on the webpage. But, it is not displaying

  • Help with sm 4.0 email and ccms

    Hi, I'm having problems generating emails in sm 4.0. I've configured the landscape in t/c solution_manager and have alerts appearing for my trainng system. I'm just checking cpu at moment. I've set the treshholds to a low value in order for alerts to

  • How to find a filed SORTL in Vendor Master

    Hi Experts, In venoder master, where to find SORTL file?  HOw to update this field? I am able to see SORT1 AND SORT2 fields but not SORTL Thanks and regards Ram

  • Please help: Mouse cursor on MBP repeatedly freezing for a few seconds

    Hi all I bought a MBP last week, and today I started experiencing problems with the mouse cursor. No matter whether I'm using the trackpad or an external mouse (I've tried using both a wired Mighty Mouse and a wireless Logitech), when I'm moving the

  • JAVA BASIC QUESTION

    The following piece of code compiles correctly: class abc double a; System.out.println("hello"); BUT THE SAME FOLLOWING CODE GIVES COMPILATION ERROR: class abc double a; System.out.println("Hello"); ---------------------------------------------