Solved

JTable

Posted on 1998-12-01
7
1,725 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_
ID: 1228555
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_
ID: 1228556
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
ID: 1228557
sounds like you need the AbstractTableModel:

  void fireTableChanged(TableModelEvent e)

or somthing like that...
 

0
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 

Author Comment

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

Author Comment

by:psteph
ID: 1228559
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
ID: 1228560
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
ID: 26126875


 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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to get all the API from website? 11 82
servlet doXXX methods 3 47
eclipse apache tomcat admin console 52 94
hibernate example using maven 12 41
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
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 will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

813 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

11 Experts available now in Live!

Get 1:1 Help Now