Solved

JTable

Posted on 1998-12-01
7
1,719 Views
Last Modified: 2009-12-27
I am displaying a sql query in a JTable.  My gui has two buttons: one to clear the table and the other to select which query the user wants to run. (I am using combo boxes to allow the choice.  I am using the following loop to clear the table:
int numRows = sdfTableModel.getRowCount();
if numRows>0)
{
    for(int i = numRows-1; i>=0; i--)
    {
        defaultTableModel.removeRow(i);
    }
}
The problem is I have two seperate tables.  The first table works fine, the second table is funky.  When you push the clear button the textfields will clear(I added that in to see if it was reaching the method) but the table wont clear..Unless you switch to another screan and then go back, the table is clear.  Or if you move the scrollbar the table clears what is not visible.  Please help.  Any Ideas??????

Thanks.....
0
Comment
Question by:psteph
  • 2
  • 2
  • 2
  • +1
7 Comments
 
LVL 16

Expert Comment

by:heyhey_
Comment Utility
it looks like you have one model with two views or some other related problem (your model cleares, but it does not informs the view)
we can help you better if post the whole UI related code ... (or even better if you post the whole code :) - please isolated COMILABLE example



0
 
LVL 16

Expert Comment

by:heyhey_
Comment Utility
and maybe it will be much more effective if you use
 public void setDataVector(Object newData[][], Object columnIds[])
for clearing the table model

hope this helps
  heyhey
0
 

Expert Comment

by:marss
Comment Utility
sounds like you need the AbstractTableModel:

  void fireTableChanged(TableModelEvent e)

or somthing like that...
 

0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:psteph
Comment Utility
Im a little confused could you give me some code ex, with these methods?
0
 

Author Comment

by:psteph
Comment Utility
Here is how I am setting up both of my tables:
String ColumnNames[] ={"one", "two", "three"}
DefaultTableModel TableModel = new DefaultTableModel(ColumnNames, 0);
JTable table = new JTable(TableModel);
0
 

Accepted Solution

by:
marss earned 100 total points
Comment Utility
import java.util.*;
import java.sql.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.event.TableModelEvent;

/**
    This Adapter is used as a 'bridge' between some database and
    JTable.

    usage is

        JTable table = new JTable(MyAdapter);
*/
public class MyAdapter extends AbstractTableModel {
      int numberOfColumns;
    String[] columnNames = {};
    Vector dataRows = new Vector();
    String defaultQuery;


    public MyAdapter(String url, String driverName, String user, String passwd, String query)
      {
            toolkit = Toolkit.getDefaultToolkit();
        try {
            Class.forName(driverName);
            connection = (OracleConnection) java.sql.DriverManager.getConnection(url, user, passwd);
            statement = (OracleStatement) connection.createStatement();
        }
        catch (ClassNotFoundException ex) {
        }
        catch (java.sql.SQLException ex) {
        }
       }


    public void executeQuery(String query) {
        try {
            resultSet = statement.executeQuery(query);
            metaData = resultSet.getMetaData();
            numberOfColumns =  metaData.getColumnCount();
            columnNames = new String[numberOfColumns];
            // Get the column names and cache them.
            // Then we can close the connection.
            for(int column = 0; column < numberOfColumns; column++) {
                columnNames[column] = metaData.getColumnLabel(column+1);
            }
            //clear current
            for(int column = 0; column < numberOfColumns; column++) {
                currentRow.addElement(null);
            }
            // Get all rows.
            rows = new Vector();
            while (resultSet.next()) {
                  Vector newRow = new Vector();
                for (int i = 1; i <= numberOfColumns; i++)
                {
                        Object o = resultSet.getObject(i);
                          newRow.addElement(o);
                }
                  rows.addElement(newRow);
                  }
        }
        catch (java.sql.SQLException ex) {
        }

// THIS IS IT !!!
//

            fireTableChanged(null);
    }


      //////////////////////////////////////////////////////////////////////////
    //
    //             Implementation of the TableModel Interface
    //
    //////////////////////////////////////////////////////////////////////////

    // MetaData

    public String getColumnName(int column) {
        if (columnNames[column] != null) {
            return columnNames[column];
        } else {
            return "";
        }
    }


    public Class getColumnClass(int column) {
        int type;
        try {
            type = metaData.getColumnType(column+1);
        }
        catch (java.sql.SQLException e) {
            return super.getColumnClass(column);
        }

        switch(type) {
              case Types.CHAR:
              case Types.VARCHAR:
              case Types.LONGVARCHAR:
                  return String.class;
              case Types.BIT:
                  return Boolean.class;

              case Types.TINYINT:
              case Types.SMALLINT:
              case Types.INTEGER:
                  return Integer.class;

              case Types.BIGINT:
                  return Long.class;

              case Types.FLOAT:
              case Types.DOUBLE:
                  return Double.class;

                  case Types.DATE:
                  return java.sql.Date.class;
              default:
                  return Object.class;
        }
    }


    public boolean isCellEditable(int row, int column) {
        try {
            return (metaData.isWritable(column+1) && (row == 0));
        }
        catch (SQLException e) {
            return false;
        }
    }


    public int getColumnCount() {
        return (columnNames.length-extraColumns.length);
    }


    // Data methods

    public int getRowCount() {
        return rows.size();
    }


    public Object getValueAt(int aRow, int aColumn) {
        try {
              Vector row = (Vector)rows.elementAt(aRow);
              return row.elementAt(aColumn);
        } catch (ArrayIndexOutOfBoundsException e) {
            return null;
        }
    }


    public void setValueAt(Object value, int row, int column) {
        String t = dbRepresentation(column, value);
        if ((t.equals("")) || (t.equals("''")))
                  currentRow.setElementAt(null, column);
        else
                  currentRow.setElementAt(value, column);
        rows.setElementAt(currentRow.clone(), 0);

// THIS IS IT !!!
//
            fireTableCellUpdated(row, column);
    }
}

0
 

Expert Comment

by:tienthinh
Comment Utility


 DefaultTableModel  a=new DefaultTableModel();
        a=      (DefaultTableModel) table.getModel();
        int numRows = table.getRowCount();
        if (numRows>0)
{
    for(int i = numRows-1; i>=0; i--)
    {
        a.removeRow(i);
    }
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now