JTable Problem(Default Table Model)

Hi all,
iam using Default Table model for my jtable i want to do pageup and pagedown operation .
TableColumnModel cm1 = new DefaultTableColumnModel();
DefaultTablemodel md = new DefaultTableModel(row,col);
JTable t = new JTable(md,cm1);
i have 500 rows currently in my database i want to display 100 in the first page and if i press the pagedown button the next 100 has to be diplayed wether this is possible here.. if possible please help mee.

sample code :
// PagingModel.java
// A larger table model that performs "paging" of its data. This model reports a
// small number of rows (e.g., 100 or so) as a "page" of data. You can switch pages
// to view all of the rows as needed using the pageDown( ) and pageUp( ) methods.
// Presumably, access to the other pages of data is dictated by other GUI elements
// such as up/down buttons, or maybe a text field that allows you to enter the page
// number you want to display.
import javax.swing.table.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class PagingModel extends AbstractTableModel {
protected int pageSize;
protected int pageOffset;
protected Record[] data;
public PagingModel( ) {
this(10000, 100);
public PagingModel(int numRows, int size) {
data = new Record[numRows];
pageSize = size;
// Fill our table with random data (from the Record( ) constructor).
for (int i=0; i < data.length; i++) {
data[i] = new Record( );
// Return values appropriate for the visible table part.
public int getRowCount( ) { return Math.min(pageSize, data.length); }
public int getColumnCount( ) { return Record.getColumnCount( ); }
// Work only on the visible part of the table.
public Object getValueAt(int row, int col) {
int realRow = row + (pageOffset * pageSize);
return data[realRow].getValueAt(col);
public String getColumnName(int col) {
return Record.getColumnName(col);
// Use this method to figure out which page you are on.
public int getPageOffset( ) { return pageOffset; }
public int getPageCount( ) {
return (int)Math.ceil((double)data.length / pageSize);
// Use this method if you want to know how big the real table is. You could also
// write "getRealValueAt( )" if needed.
public int getRealRowCount( ) {
return data.length;
public int getPageSize( ) { return pageSize; }
public void setPageSize(int s) {
if (s == pageSize) { return; }
int oldPageSize = pageSize;
pageSize = s;
pageOffset=(oldPageSize * pageOffset) / pageSize;
fireTableDataChanged( );
// Update the page offset and fire a data changed event (all rows).
public void pageDown( ) {
if (pageOffset < getPageCount( ) - 1) {
pageOffset++;
fireTableDataChanged( );
// Update the page offset and fire a data changed (all rows).
public void pageUp( ) {
if (pageOffset > 0) {
pageOffset--;
fireTableDataChanged( );
// We provide our own version of a scrollpane that includes
// the Page Up and Page Down buttons by default.
public static JScrollPane createPagingScrollPaneForTable(JTable jt) {
JScrollPane jsp = new JScrollPane(jt);
TableModel tmodel = jt.getModel( );
// Don't choke if this is called on a regular table . . .
if (! (tmodel instanceof PagingModel)) {
return jsp;
// Go ahead and build the real scrollpane.
final PagingModel model = (PagingModel)tmodel;
final JButton upButton = new JButton("Up");
upButton.setEnabled(false); // Starts off at 0, so can't go up
final JButton downButton = new JButton("Down");
if (model.getPageCount( ) <= 1) {
downButton.setEnabled(false); // One page...can't scroll down
upButton.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent ae) {
model.pageUp( );
// If we hit the top of the data, disable the Page Up button.
if (model.getPageOffset( ) == 0) {
upButton.setEnabled(false);
downButton.setEnabled(true);
downButton.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent ae) {
model.pageDown( );
// If we hit the bottom of the data, disable the Page Down button.
if (model.getPageOffset( ) == (model.getPageCount( ) - 1)) {
downButton.setEnabled(false);
upButton.setEnabled(true);
// Turn on the scrollbars; otherwise, we won't get our corners.
jsp.setVerticalScrollBarPolicy
(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jsp.setHorizontalScrollBarPolicy
(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
// Add in the corners (page up/down).
jsp.setCorner(ScrollPaneConstants.UPPER_RIGHT_CORNER, upButton);
jsp.setCorner(ScrollPaneConstants.LOWER_RIGHT_CORNER, downButton);
return jsp;
// Record.java
// A simple data structure for use with the PagingModel demo
class Record {
static String[] headers = { "Record Number", "Batch Number", "Reserved" };
static int counter;
String[] data;
public Record( ) {
data = new String[] { "" + (counter++), "" + System.currentTimeMillis( ),
"Reserved" };
public String getValueAt(int i) { return data[i]; }
public static String getColumnName(int i) { return headers[i]; }
public static int getColumnCount( ) { return headers.length; }
class PagingTester extends JFrame {
public PagingTester( ) {
super("Paged JTable Test");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
PagingModel pm = new PagingModel( );
JTable jt = new JTable(pm);
// Use our own custom scrollpane.
JScrollPane jsp = PagingModel.createPagingScrollPaneForTable(jt);
getContentPane( ).add(jsp, BorderLayout.CENTER);
public static void main(String args[]) {
PagingTester pt = new PagingTester( );
pt.setVisible(true);
}

Similar Messages

  • Jtable, sql, default table model

    Hi all,
    I need help. How do I create JTable, generaly Default table model and query which will work with the database. Thx.

    Look to this example
    [http://jfxstudio.wordpress.com/2009/05/25/the-graphic-database-front-end-ii/|http://jfxstudio.wordpress.com/2009/05/25/the-graphic-database-front-end-ii/]
    tables, database and advanced graphics

  • Is it posiible to paging up paging down in Jtable using Default Table Model

    Hi All!
    Is it possible to do Page up and Page down in JTable using Default Tble Model?
    Kindly reply!

    yes
    it is posiible to paging up paging down in Jtable using Default Table Model. just go thru the JAVA API you will get the results.

  • PageUp/PageDown By using Default Table Model

    Hi all,
    iam using Default Table model for my jtable i want to do pageup and pagedown operation .
    TableColumnModel cm1 = new DefaultTableColumnModel();
    DefaultTablemodel md = new DefaultTableModel(row,col);
    JTable t = new JTable(md,cm1);
    i have 500 rows currently in my database i want to display 100 in the first page and if i press the pagedown button the next 100 has to be diplayed wether this is possible here.. if possible please help mee.

    Hi,
    could you please avoid double posting:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=566380&tstart=0&trange=15
    especially with different subjects.
    It considerably reduces the overall efficiency as people will try to
    help you while the answer could already have been given in the another thread.
    If you want to push up the stack your message, reply to it,
    post more code, list the ideas that you've envisaged and so on.
    regards.

  • Setting row identifiers in default table model

    hey i'm making a default table model and i cant figure out how to make a row have an identifier. the column one is setColumnIdentifiers but there isn't a code that i could find for a row.. please help thanx kevin

    You are correct, JTable does not support a TableRowModel, therefore it does not support setRowIdentifiers.
    I'm not sure exactly what your requirement is so its hard to make a suggestion. You could add an extra column to your table to contain a row identifier. You could then remove this column from the TableColumnModel to prevent this column from being painted. This [url http://forum.java.sun.com/thread.jsp?forum=31&thread=411506]thread shows how to remove a column from the table.

  • Problem with Table Model Listener

    I hava a JTable with three columns and dynamic number of rows. The first column has a text. Second column has check box and each third column has three radio buttons. I am using the table model listener to fetch the row and column which the user clicked. here is the code
    public void tableChanged(TableModelEvent e)
    row = e.getFirstRow();
    column = e.getColumn();
    TableModel model = (TableModel)e.getSource();
    String columnName = model.getColumnName(column);
    Object value = model.getValueAt(row, column);
    System.err.println("Value: "<em>value.toString()</em>" Row: "<em>row</em>" Column: "+column);
    attendanceModel.setHolidays(row, value.toString());
    }Here is the problem
    {color:#ff0000}Case 1{color}: When I click the first radio button in first row and third column it works and the output of print statement is
    *{color:#993300}Value:0 Row:0 Column:2{color}*
    {color:#ff0000}Case 2{color}: Next I clicked the first radio button in second row and third column the method is not called nothing is printed
    {color:#ff0000}Case 3{color}: Now I clicked the first radio button in third row and thrid column, the method is called and the output of print statement is
    {color:#993300}*Value:0 Row:1 Column:2*{color} ; but the actual value of row should be 2*. Here it is showing the row and column of the previously selected item.
    But in {color:#ff0000}case 2{color} instead of first radio button if I selected the second radio button the print statement will print the correct value i.e
    {color:#993300}*Value:1 Row:1 Column:2*{color}
    ie If I select different radio button in each row the print statement shows the correct value. But if in each row the same radio button is selected its not working properly. For first row it prints properly. If same radio button is selected in second row the method is not called. But from next row onwards the row value is showing the previously selected row as in {color:#ff0000}case 3{color}.
    But for the checkboxes in column 2 the same is working properly. Each column has only one check box. So when I select the check box in each row the row and column values are getting changed accordingly.
    Could some one help please?
    Thanks,
    Zach.

    To get better help sooner, post a [SSCCE (Short, Self Contained, Compilable and Executable, Example Program)|http://mindprod.com/jgloss/sscce.html] that demonstrates the incorrect behaviour.
    db

  • Custom Table Model from Default Table Model

    I'm creating a customised table model to create a table with column header and empty rows.But it is throwing Component paint_imediatly error.If i pass in empty string to the row vector then setNumRows then no problem. If i do like this later it throws me error in my addNewRow method which was working fine before.Can anyone help?I would realy apreaciate it.Thank you.
    Kavitha

    This must be your lucky day :)
    Here is my version of an EditableTableModel which displays an emptyline as the last line
    import java.io.*;
    import java.util.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    * Custom TableModel, allows addition and removal of records/rows and editting of existing values.
    * it also keeps track over which rows have been altered.
    * column 0 is a boolean indicating wheter or not to keep this row/record
    * @author Maurice Marrink
    * @version 1.0
    public class EditableTableModel extends AbstractTableModel implements Serializable, TableModelListener
         protected ArrayList keep,changed;          //houden bij of een rij gedel moet worden en of ie is veranderd (false = delete)
         protected ArrayList[] DATA;
         protected int emptyLineIndex;
         protected String[] kolomNamen;
         protected Object[] kolomTypen;          // bevat een object van dezelfde class als die kolom
         protected int newRowsIndex;               // houd bij vanaf welke rij niewe regels zijn toegevoegd ivm het opslaan in de db
         protected int[]primecolumns;          //houd bij welke kolommen ingevuld moeten worden voordat de volgende regel getoond wordt (default= kolom 1)
         public EditableTableModel()
              keep = new ArrayList();               //visible
              changed=new ArrayList();               // not visisble
              primecolumns=new int[0];
              DATA=new ArrayList[0];
              kolomNamen =new String[0];
              kolomTypen=new Object[0];
              emptyLineIndex=-1;
              newRowsIndex=-1;
         * the constructor, creates a new EditableTableModel
         *@param data          an array of ArrayLists each arrayList contains the values of an entire column
         *@param names          an array containg the names of the columns
         *@param type          an array containing Objects which correspond to the objects in the columns
         public EditableTableModel(ArrayList[] data, String[] names, Object[] type)
              keep = new ArrayList();               //visible
              changed=new ArrayList();               // not visisble     
              primecolumns=new int[1];
              primecolumns[0]=1;
              DATA=data;
              for(int i=0;i<getRowCount();i++)
                   keep.add(new Boolean(true));
                   changed.add(new Boolean(false));
              kolomNamen=names;
              kolomTypen=type;
              emptyLineIndex=getRowCount()-1;
              addNewLine();
              newRowsIndex=emptyLineIndex;               // nieuwe regels beginnen op de lege regel
              addTableModelListener(this);
         * @return the number of rows/records
         public int getRowCount()
              return DATA[0].size();
         *@return the number of columns
         public int getColumnCount()
              return DATA.length+1;
         * returns the object containing the value for this cell
         * indexes start at 0 (wheter or not to keep this row), but the actual data starts at 1
         *@param row          the row in which the cell resides
         *@param column     the column in which the cell resides
         *@return the value of the cell wrapped in the appropiate Object
         public Object getValueAt(int row, int column)
              if(column==0)
                   return keep.get(row);
              else
                   return DATA[column-1].get(row);
         * allows editing of an existing value
         *@param value          the new value, should be of the same Object Type as the existing one
         *@param row               the row nr of the cell
         *@param col               the column nr of the cell
         public void setValueAt(Object value, int row, int col)
              if(col==0)
                   keep.set(row,value);
              else
                   DATA[col-1].set(row,value);
                   changed.set(row, new Boolean(true));
              fireTableCellUpdated(row, col);
         * adds a new "empty" row after all the PrimeColums of the last row have been filled with an acceptable value
         *@see setPrimeColumns
         protected void addNewLine()
              try
                   for(int i=0;i<DATA.length;i++)
                        if(kolomTypen[i] instanceof Integer)
                             DATA.add(new Integer(-1));
                        else
                        if(kolomTypen[i] instanceof Boolean)
                             DATA[i].add(new Boolean(false));
                        else
                        if(kolomTypen[i] instanceof Long)
                             DATA[i].add(new Long(-1));          //displayed as "" by cellrenderer
                        else
                             DATA[i].add(kolomTypen[i].getClass().newInstance());          //nieuw object aanmaken van het type dat gespecificeerd is, Integers en Booleans moet een waarde meegegeven worden
                   keep.add(new Boolean(true));
                   changed.add(new Boolean(false));
                   emptyLineIndex++;
              catch(Exception e)
                   e.printStackTrace();
         public void tableChanged(TableModelEvent e)
              if(e.getFirstRow()==emptyLineIndex)//alleen als de emptyLine ge?dit wordt een regel toevoegen
                   boolean primesfilled=true;
                   for(int i=0;i<primecolumns.length;i++)
                        if(getValueAt(emptyLineIndex,primecolumns[i]).equals(null) || getValueAt(emptyLineIndex,primecolumns[i]).toString().equals("")|| getValueAt(emptyLineIndex,primecolumns[i]).toString().equals("-1"))
                             primesfilled=false;
                             break;
                   if(primesfilled)     //alleen als de primaire sleutel kolommen ingevuld zijn
                        addNewLine();
         * returns the Class type of the Objects representing the column type
         *@param c     the column nr
         public Class getColumnClass(int c)
              if(c==0)
                   return new Boolean(true).getClass();
              else
                   return kolomTypen[c-1].getClass();
         *@param rowIndex the index of the row
         *@param columnIndex     the index of the column
         *@return true if a cell is Editable,false otherwise (all cells are Editable)
         public boolean isCellEditable(int rowIndex, int columnIndex)
              return true;
         * returns the name of the column
         *@param column     the column index
         *@return a String containing the name of the column
         public String getColumnName(int column)
              if(column==0)
                   return "";
              else
                   return kolomNamen[column-1];
         *@return wheter or not 1 or rows is marked for deletion
         public boolean deletionNeeded()
              Boolean B;
              for(int i=0;i<emptyLineIndex;i++)
                   B=(Boolean)keep.get(i);
                   if(!B.booleanValue())
                        return true;
              return false;
         * Deletes all rows which are marked for deletion
         *@return the number of rows that have been deleted
         public int deleteMarkedRows()          // zou niets uit moeten maken of je eerst deleteMarkedRows() of isSavedToDB(true) aanroept
              int aantalRows=0;
              Boolean B;
              for(int i=0;i<emptyLineIndex;i++)
                   B=(Boolean)keep.get(i);
                   if(!B.booleanValue())
                        if(deleteRow(i))
                             aantalRows++;
                             i--;
              return aantalRows;
         * deletes a single row
         *@param row     the row index
         *@return     true if the row was deleted, false otherwise
         protected boolean deleteRow(int row)
              boolean result=false;
              if(row==emptyLineIndex)               // emptyline kan niet gedelete worden
                   return result;
              try
                   for(int j=0;j<DATA.length;j++)
                        DATA[j].remove(row);
                   changed.remove(row);
                   keep.remove(row);
                   emptyLineIndex--;
                   if(row < newRowsIndex)
                        newRowsIndex--;
                   result=true;
              catch(Exception e)
                   e.printStackTrace();
              return result;
         * returns if the row has changed or not
         *@param row          the row index
         *@return true if 1 or more cells in this row had their value changed or if 1 or more rows were added, false otherwise
         public boolean hasChanged(int row)
              Boolean B=(Boolean)changed.get(row);
              return B.booleanValue();
         * Methode waarmee men kan bepalen of 1 van de originele waarden ook veranderd is.
         * Het geeft dus niet aan of er ook nieuwe rijen zijn toegevoegd.
         public boolean hasChanged()
              Boolean B;
              for(int i=0;i<newRowsIndex;i++)
                   B=(Boolean)changed.get(i);
                   if(B.booleanValue())
                        return true;
              return false;
         * if true it sets all flags indicating a change to false, else nothing
         *@param saved     boolean indicating all changes are now to be considerd to be the original values, or not
         public void isSavedToDB(boolean saved)
              if(saved)
                   for(int i=0; i<changed.size();i++)
                        changed.set(i,new Boolean(false));
                   newRowsIndex=emptyLineIndex;
         * @return the row nr. at which newly added entrys begin, updated after isSavedToDB(true) is called
         public int getNewRowsIndex()
              return newRowsIndex;
         * allows the specification of certain columns that need to be filled in, if not a new row will not be made vissible
         *@param columns     an array containing the column indexes which must be set to a valid value
         public void setPrimeColumns(int[] columns)
              primecolumns=columns;
         * allows retrieval of the PrimeColumns
         *@return an arrayof int containing the column indexes
         public int[] getPrimeColumns()
              return primecolumns;
    Ok some of the comments are in dutch go ahead an blame me :(
    if you have any questions, just ask.
    i also have a TableModel which can use automatic numbering
    Oh numbers (currently only Integer and Long) are initiated wth a value of -1 if you want to display them as blank cells like i wanted to you modify a cellrenderer (or use mine)
    Mr Mean

  • Transfer Data from a JTable to the table model

    Hi
    I' looking for a simple method to transfer the last user input in a table to the table model.
    For example:
    In a Dialog the user insert in a JTable a few values and leaves with OK. But the last input is not saved in the model. It is just saved after selecting a new field in the JTable before leaving the Dialog.
    Is there a call to transfer all input to the model?
    Thanks
    Guido

    class MyJTable extends JTable (
    public boolean validateInput() {
    if(isEditing()) {
    return cellEditor.stopCellEditing();
    return true;
    Call this method whenever you want the input value to be stored in the table model. The return value can be false if the input isn't valid, this will depend on the cell editor.
    The idea is:
    Ask if the table has an editor activated. (isEditing())
    If so, request the editor to store the value in the model.
    I haven't prouved the code, sorry, but I hope you get the idea and helps.

  • JButton in JTable with custom table model

    Hi!
    I want to include a JButton into a field of a JTable. I do not know why Java does not provide a standard renderer for JButton like it does for JCheckBox, JComboBox and JTextField. I found some previous postings on how to implement custom CellRenderer and CellEditor in order to be able to integrate a button into the table. In my case I am also using a custom table model and I was not able to create a clickable button with any of the resources that I have found. The most comprehensive resource that I have found is this one: http://www.java2s.com/Code/Java/Swing-Components/ButtonTableExample.htm.
    It works fine (rendering and clicking) when I start it. However, as soon as I incorporate it into my code, the clicking does not work anymore (but the buttons are displayed). If I then use a DefaultTableModel instead of my custom one, rendering and clicking works again. Does anyone know how to deal with this issue? Or does anyone have a good pointer to a resource for including buttons into tables? Or does anyone have a pointer to a resource that explains how CellRenderer and CellEditor work and which methods have to be overwritten in order to trigger certain actions (like a button click)?
    thanks

    Yes, you were right, the TableModel was causing the trouble, everything else worked fine. Somehow I had this code (probably copy and pasted from a tutorial - damn copy and pasting) in my TableModel:
            public boolean isCellEditable(int row, int col) {
                //Note that the data/cell address is constant,
                //no matter where the cell appears onscreen.
                if (col < 3) {
                    return false;
                } else {
                    return true;
    }A pretty stupid thing when you want to edit the 3rd column...

  • How to add image in jtable header using 'Default table model'

    Hi,
    I created a table using "DefaultTableModel".
    im able to add images in table cells but not in 'table header'.
    i added inages in table by overriding "getColumnClass" of the DefaultTableModel.
    But what to do for headers?
    please help.
    Thanks in advance.

    The 'Java 5 tutorial' is really an outstanding oneI should note the the current tutorial on the Sun website has bee updated for Java 6. It contains updates to reflect the changes made in JDK6. Once of the changes is that sorting of tables is now supported directly which is why I needed to give you the link to the old tutorial.
    http://java.sun.com/docs/books/tutorial/uiswing/TOC.html

  • Help for adjusting columns of a JTAble in a Table Model

    Hello community,
    In order to have a good display of by DataBase in a JTable, I've wrote some code to adjust columns in function of datas. Those datas are displayed with a TableModel ( which I've declared in a class JDBCAdapter ).
    When I start my application, I call adjustColumns(), and all is great but when I add information to my DB and display it, the columns of my JTable return to default width...
    So I want to incorporate my function adjustColumns in my TableModel, and I need help...
         void adjustColumns()
         // Ajuste les colonnes aux donnes pour que tout soit visible
         int nbRow,nbCol;
         nbRow = JTable1.getRowCount();
         nbCol = test.getColumnCount();
         for ( int i = 0; i < nbCol; i++ )
         com.sun.java.swing.table.TableColumn column = null;
         column = JTable1.getColumnModel().getColumn(i);
         int dataLength = 0;
         for ( int j = 0; j< nbRow; j++ )
         FontMetrics fm;
         int dataLengthTmp;
         String valueTable;
         fm = JTable1.getFontMetrics(JTable1.getFont());
         if ( test.getValueAt(j, i) == null )
         System.out.println("Valeur nulle...");
         dataLengthTmp = 0;
         else
         valueTable = test.getValueAt(j, i).toString();
         dataLengthTmp = fm.stringWidth(valueTable);
         System.out.println(valueTable + " = " + dataLengthTmp);
         if ( dataLengthTmp > dataLength )
         dataLength = dataLengthTmp;
         if ( dataLength != 0 )
    column.setWidth(dataLength + 5);
    else
    column.sizeWidthToFit();
    JTable1.setModel(test);
    JTable1.repaint();
    import java.util.Vector;
    import java.sql.*;
    import com.sun.java.swing.table.AbstractTableModel;
    import com.sun.java.swing.event.TableModelEvent;
    public class JDBCAdapter extends AbstractTableModel {
    Connection connection;
    Statement statement;
    ResultSet resultSet;
    String[] columnNames = {};
    Vector rows = new Vector();
    ResultSetMetaData metaData;
    public JDBCAdapter(String url, String driverName,
    String user, String passwd) {
    try {
    Class.forName(driverName);
    System.out.println("Ouverture de la connexion a la base de donnee...");
    connection = DriverManager.getConnection(url, user, passwd);
    statement = connection.createStatement();
    catch (ClassNotFoundException ex) {
    System.err.println("Cannot find the database driver classes.");
    System.err.println(ex);
    catch (SQLException ex) {
    System.err.println("Cannot connect to this database.");
    System.err.println(ex);
    public void executeQuery(String query) {
    if (connection == null || statement == null) {
    System.err.println("There is no database to execute the query.");
    return;
    try {
    resultSet = statement.executeQuery(query);
    metaData = resultSet.getMetaData();
    int 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);
    // Get all rows.
    rows = new Vector();
    while (resultSet.next()) {
    Vector newRow = new Vector();
    for (int i = 1; i <= getColumnCount(); i++) {
    newRow.addElement(resultSet.getObject(i));
    rows.addElement(newRow);
    // close(); Need to copy the metaData, bug in jdbc:odbc driver.
    fireTableChanged(null); // Tell the listeners a new table has arrived.
    catch (SQLException ex) {
    System.err.println(ex+" query = "+query);
    public void executeUpdate(String query) {
    if (connection == null || statement == null) {
    System.err.println("There is no database to execute the query.");
    return;
    try {
    statement.executeUpdate(query);
    // close(); Need to copy the metaData, bug in jdbc:odbc driver.
    fireTableChanged(null); // Tell the listeners a new table has arrived.
    catch (SQLException ex) {
    System.err.println(ex+" query = "+query);
    public void close() throws SQLException {
    System.out.println("Fermeture de la connection a la base de donnee... Bye !");
    resultSet.close();
    statement.close();
    connection.close();
    protected void finalize() throws Throwable {
    close();
    super.finalize();
    // 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 (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);
    catch (SQLException e) {
    return false;
    public int getColumnCount() {
    return columnNames.length;
    // Data methods
    public int getRowCount() {
    return rows.size();
    public Object getValueAt(int aRow, int aColumn) {
    Vector row = (Vector)rows.elementAt(aRow);
    return row.elementAt(aColumn);
    public String dbRepresentation(int column, Object value) {
    int type;
    if (value == null) {
    return "null";
    try {
    type = metaData.getColumnType(column+1);
    catch (SQLException e) {
    return value.toString();
    switch(type) {
    case Types.INTEGER:
    case Types.DOUBLE:
    case Types.FLOAT:
    return value.toString();
    case Types.BIT:
    return ((Boolean)value).booleanValue() ? "1" : "0";
    case Types.DATE:
    return value.toString(); // This will need some conversion.
    default:
    return "\""+value.toString()+"\"";
    public void setValueAt(Object value, int row, int column) {
    try {
    String tableName = metaData.getTableName(column+1);
    // Some of the drivers seem buggy, tableName should not be null.
    if (tableName == null) {
    System.out.println("Table name returned null.");
    String columnName = getColumnName(column);
    String query =
    "update "+tableName+
    " set "+columnName+" = "+dbRepresentation(column, value)+
    " where ";
    // We don't have a model of the schema so we don't know the
    // primary keys or which columns to lock on. To demonstrate
    // that editing is possible, we'll just lock on everything.
    for(int col = 0; col<getColumnCount(); col++) {
    String colName = getColumnName(col);
    if (colName.equals("")) {
    continue;
    if (col != 0) {
    query = query + " and ";
    query = query + colName +" = "+
    dbRepresentation(col, getValueAt(row, col));
    System.out.println(query);
    System.out.println("Not sending update to database");
    // statement.executeQuery(query);
    catch (SQLException e) {
    // e.printStackTrace();
    System.err.println("Update failed");
    Vector dataRow = (Vector)rows.elementAt(row);
    dataRow.setElementAt(value, column);
    Thanks to help me.

    Hi,
    OK. I have read your code sample again. It looks like the JDBCAdapter class is reloading table data in the executeQuery method. Why not call adjustColumns at the end of this method after the new rows and columns are loaded? Perhaps it also should be called at the end of executeUpdate. Have you tried doing that?
    I would still set
    JTable1.setAutoCreateColumnsFromModel (false); to prevent Java from readjusting the size automatically at some other time.
    regards,
    Terry

  • JTable Problem (table does not show rows and columns)

    Hi All,
    What the table is suppose to do.
    - Load information from a database
    - put all the values in the first column
    - in the second column put combobox (cell editor with numbers 1-12)
    - the 3rd column put another combobox for something else
    - the 4th column uses checkbox as an edit
    The number of rows of the table should be equal to the number of
    record from
    the database. If not given it default to 20 (poor but ok for this)
    The number of columns is 4.
    But the table does not show any rows or
    column when I put it inside a
    JScrollPane (Otherwise it works).
    Please help,
    thanks in advance.
    public class SubjectTable extends JTable {
    * Comment for <code>serialVersionUID</code>
    private static final long serialVersionUID = 1L;
    /** combo for the list of classes */
    protected JComboBox classCombo;
    /** combo for the list of subjects */
    protected JComboBox subjectsCombo;
    /** combo for the list of grade */
    protected JComboBox gradeCombo;
    boolean canResize = false;
    boolean canReorder = false;
    boolean canSelectRow = false;
    boolean canSelectCell = true;
    boolean canSelectColumn = true;
    // the row height of the table
    int rowHeight = 22;
    // the height of the table
    int height = 200;
    // the width of the table
    int width = 300;
    // the size of the table
    Dimension size;
    * Parameterless constructor. Class the one of the other constructors
    to
    * create a table with the a new <code>SubjectTableModel</code>.
    public SubjectTable() {
    this(new SubjectTableModel());
    * Copy constructor to create the table with the given
    * <code>SubjectTableModel</code>
    * @param tableModel -
    * the <code>SubjectTableModel</code> with which to
    initialise
    * the table.
    SubjectTable(SubjectTableModel tableModel) {
    setModel(tableModel);
    setupTable();
    * Function to setup the table's functionality
    private void setupTable() {
    clear();
    // set the row hieght
    this.setRowHeight(this.rowHeight);
    // set the font size to 12
    //TODO this.setFont(Settings.getDefaultFont());
    // disble reordering of columns
    this.getTableHeader().setReorderingAllowed(this.canReorder);
    // disble resing of columns
    this.getTableHeader().setResizingAllowed(this.canResize);
    // enable the horizontal scrollbar
    this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    // disable row selection
    setRowSelectionAllowed(this.canSelectRow);
    // disable column selection
    setColumnSelectionAllowed(this.canSelectColumn);
    // enable cell selection
    setCellSelectionEnabled(this.canSelectCell);
    setPreferredScrollableViewportSize(getSize());
    TableColumn columns = null;
    int cols = getColumnCount();
    for (int col = 0; col < cols; col++) {
    columns = getColumnModel().getColumn(col);
    switch (col) {
    case 0:// subject name column
    columns.setPreferredWidth(130);
    break;
    case 1:// grade column
    columns.setPreferredWidth(60);
    break;
    case 2:// class room column
    columns.setPreferredWidth(120);
    break;
    case 3:// select column
    columns.setPreferredWidth(65);
    break;
    } // end switch
    }// end for
    // set up the cell editors
    doGradeColumn();
    doClassColumn();
    //doSubjectColumn();
    * Function to clear the table selection. This selection is different
    to
    * <code>javax.swing.JTable#clearSelection()</code>. It clears the
    user
    * input
    public void clear() {
    for (int row = 0; row < getRowCount(); row++) {
    for (int col = 0; col < getColumnCount(); col++) {
    if (getColumnName(getColumnCount() - 1).equals("Select")) {
    setValueAt(new Boolean(false), row, getColumnCount() - 1);
    }// if
    }// for col
    }// for row
    * Function to set the cell renderer for the subjects column. It uses
    a
    * combobox as a cell editor in the teacher's subjects table.
    public void doSubjectColumn() {
    TableColumn nameColumn = getColumnModel().getColumn(0);
    nameColumn.setCellEditor(new DefaultCellEditor(getSubjectsCombo()));
    // set up the celll renderer
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for drop down list");
    nameColumn.setCellRenderer(renderer);
    // Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = nameColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer) headerRenderer)
    .setToolTipText("Click the Name to see a list of choices");
    }// end doSubjectsColumn----------------------------------------------
    /** Function to set up the grade combo box. */
    public void doGradeColumn() {
    TableColumn gradeColumn = getColumnModel().getColumn(1);
    gradeColumn.setCellEditor(new DefaultCellEditor(getGradeCombo()));
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for drop down list");
    gradeColumn.setCellRenderer(renderer);
    // Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = gradeColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer) headerRenderer)
    .setToolTipText("Click the Grade to see a list of choices");
    }// end doGradeColumn-------------------------------------------------
    * Function to setup the Class room Column of the subjects
    public void doClassColumn() {
    // set the column for the classroom
    TableColumn classColumn = getColumnModel().getColumn(2);
    classColumn.setCellEditor(new DefaultCellEditor(getClassCombo()));
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for drop down list");
    classColumn.setCellRenderer(renderer);
    // Set up tool tip for the sport column header.
    TableCellRenderer headerRenderer = classColumn.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer) {
    ((DefaultTableCellRenderer) headerRenderer)
    .setToolTipText("Click the Class to see a list of choices");
    }// end doClassColumn--------------------------------------------------
    * Function to get the size of the table
    * @return Returns the size.
    public Dimension getSize() {
    if (this.size == null) {
    this.size = new Dimension(this.height, this.width);
    return this.size;
    * Function to set the size of the table
    * @param dim
    * The size to set.
    public void setSize(Dimension dim) {
    if (dim != null) {
    this.size = dim;
    return;
    * Function to create/setup the class room comboBox. If the comboBox
    is
    * <code>null</code> a nwew one is created else the functon returns
    the
    * function that was returned initially.
    * @return Returns the classCombo.
    private JComboBox getClassCombo() {
    if (this.classCombo == null) {
    this.classCombo = new JComboBox();
    // fill up the class name combo
    ArrayList classRooms = new ArrayList();
    try {
    //TODO classRooms = Settings.getDatabase().getClassRooms();
    for (int i = 0; i < 10; i++) {
    String string = new String("Class");
    string += i;
    if (!classRooms.isEmpty()) {
    classRooms.trimToSize();
    for (int i = 0; i < classRooms.size(); i++) {
    this.classCombo.addItem(classRooms.get(i));
    } catch (Exception e) {
    e.printStackTrace();
    return this.classCombo;
    * Function to create/setup the subjects comboBox. If the comboBox is
    * <code>null</code> a nwew one is created else the functon returns
    the
    * function that was returned initially.
    * @return Returns the subjectsCombo.
    private JComboBox getSubjectsCombo() {
    if (this.subjectsCombo == null) {
    this.subjectsCombo = new JComboBox();
    try {
    ArrayList subjects = loadSubjectsFromDatabase();
    if (!subjects.isEmpty()) {
    Iterator iterator = subjects.iterator();
    while (iterator.hasNext()) {
    // create a new subject instance
    //TODO Subject subct = new Subject();
    // typecast to subject
    //TODO subct = (Subject) iterator.next();
    String name = (String) iterator.next();
    // add this subject to the comboBox
    //TODO this.subjectsCombo.addItem(subct.getName());
    subjectsCombo.addItem(name);
    }// end while
    }// end if
    else {
    JOptionPane.showMessageDialog(SubjectTable.this,
    "Subjects List Could Not Be Filled");
    System.out.println("Subjects List Could Not Be Filled");
    } catch (Exception e) {
    e.printStackTrace();
    return this.subjectsCombo;
    * Function to load subjects from the <code>Database</code>
    * @return Returns the subjects.
    private ArrayList loadSubjectsFromDatabase() {
    // list of all the subject that the school does
    ArrayList subjects = new ArrayList();
    try {
    //TODO to be removed later on
    for (int i = 0; i < 10; i++) {
    String string = new String("Subject");
    string += i;
    subjects.add(i, string);
    // set the school subjects
    //TODO subjects = Settings.getDatabase().loadAllSubjects();
    } catch (Exception e1) {
    e1.printStackTrace();
    return subjects;
    * Function to create/setup the grade comboBox. If the comboBox is
    * <code>null</code> a nwew one is created else the functon returns
    the
    * function that was returned initially.
    * @return Returns the gradeCombo.
    private JComboBox getGradeCombo() {
    if (this.gradeCombo == null) {
    this.gradeCombo = new JComboBox();
    // fill with grade 1 to 12
    for (int i = 12; i > 0; i--) {
    this.gradeCombo.addItem(new Integer(i).toString());
    return this.gradeCombo;
    public static void main(String[] args) {
    try {
    UIManager.setLookAndFeel(new Plastic3DLookAndFeel());
    System.out.println("Look and Feel has been set");
    } catch (UnsupportedLookAndFeelException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    SubjectTableModel model = new SubjectTableModel();
    int cols = model.getColumnCount();
    int rows = model.getRowCount();
    Object[][] subjects = new Object[rows][cols];
    for (int row = 0; row < rows; row++) {
    subjects[row][0] = new String("Subjectv ") + row;
    }//for
    model.setSubjectsList(subjects);
    SubjectTable ttest = new SubjectTable(model);
    JFrame frame = new JFrame("::Table Example");
    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setViewportView(ttest);
    frame.getContentPane().add(scrollPane);
    frame.pack();
    frame.setVisible(true);
    **************************************END
    TABLE******************************
    ----------------------------THE TABLE
    MODEL----------------------------------
    * Created on 2005/03/21
    * SubjectTableModel
    package com.school.academic.ui;
    import javax.swing.table.AbstractTableModel;
    * Class extending the <code>AbstractTableModel</code> for use in
    creating the
    * <code>Subject</code>s table. In addition to the implemented methods
    of
    * <code>AbstractTableModel</code> The class creates a model that has
    initial
    * values - the values have their own <code>getter</code> and
    * <code>setter</code> methods - but can still be used for values that
    a user
    * chooses.
    * <p>
    * @author Khusta
    public class SubjectTableModel extends AbstractTableModel {
    * Comment for <code>serialVersionUID</code>
    private static final long serialVersionUID = 3257850978324461113L;
    /** Column names for the subjects table */
    String[] columnNames = { "Subject", "Grade", "Class Room",
    "Select" };
    /** Array of objects for the subjects table */
    Object[][] subjectsList;
    private int totalRows = 20;
    protected int notEditable = 0;
    * Parameterless constructor.
    public SubjectTableModel() {
    // TODO initialise the list
    // add column to the default table model
    this.subjectsList = new
    Object[getTotalRows()][getColumnNames().length];
    * Copy constructor with the <code>subjectList</code> to set
    * @param subjects
    public SubjectTableModel(Object[][] subjects) {
    this(0, null, subjects, 0);
    * Copy constructor with the initial number of row for the model
    * @param rows -
    * the initial rows of the model
    * @param cols -
    * the initial columns of the model
    * @param subjects -
    * the initial subjects for the model
    * @param edit - the minimum number of columns that must be
    uneditable
    public SubjectTableModel(int rows, String[] cols, Object[][]
    subjects, int edit) {
    // set the initial rows
    setTotalRows(rows);
    // set the column names
    setColumnNames(cols);
    // set the subjectlist
    setSubjectsList(subjects);
    //set not editable index
    setNotEditable(edit);
    * Function to get the total number of columns in the table
    * @return int -- the columns in the table
    public int getColumnCount() {
    if (this.subjectsList == null) {
    return 0;
    return getColumnNames().length;
    * Function to get the total number of rows in the table
    * @return int -- the rows in the table
    public int getRowCount() {
    if (this.subjectsList == null) {
    return 0;
    return this.subjectsList.length;
    * Function to get the name of a column in the table.
    * @param col --
    * the column to be named
    * @return String -- the column in the table
    public String getColumnName(int col) {
    if (getColumnNames()[col] != null) {
    return getColumnNames()[col];
    return new String("...");
    * Function to get the value of the given row.
    * @param row --
    * the row of the object.
    * @param col --
    * the col of the object.
    * @return Object -- the value at row, col.
    public Object getValueAt(int row, int col) {
    return getSubjectsList()[row][col];
    * Function to return the data type of the given column.
    * @param c --
    * the column whose type must be determined.
    * @return Class -- the type of the object in this col.
    public Class getColumnClass(int c) {
    if (getValueAt(0, c) != null) {
    return getValueAt(0, c).getClass();
    return new String().getClass();
    * Function to put a value into a table cell.
    * @param value --
    * the object that will be put.
    * @param row --
    * the row that the object will be put.
    * @param col --
    * the col that the object will be put.
    public void setValueAt(Object value, int row, int col) {
    * TODO: Have a boolean value to determine whether to clear or
    to set.
    * if true clear else set.
    if (value != null) {
    if (getSubjectsList()[0][col] instanceof Integer
    && !(value instanceof Integer)) {
    try {
    getSubjectsList()[row][col] = new
    Integer(value.toString());
    fireTableCellUpdated(row, col);
    } catch (NumberFormatException e) {
    * JOptionPane .showMessageDialog( this., "The \""
    +
    * getColumnName(col) + "\" column accepts only
    values
    * between 1 - 12");
    return;
    System.out.println("Value = " + value.toString());
    System.out.println("Column = " + col + " Row = " + row);
    // column = Grade or column = Select
    switch (col) {
    case 2:
    try {
    // TODO
    if (Boolean.getBoolean(value.toString()) == false
    && getValueAt(row, 0) != null
    && getValueAt(row, 1) != null
    && getValueAt(row, 2) != null) {
    // subjectsList[row][col + 1] = new
    Boolean(true);
    System.out.println("2. false - Updated...");
    * this.subjectListModel.add(row,
    * this.subjectsList[row][0] + new String(" -
    ") +
    * this.subjectsList[row][2]);
    } catch (ArrayIndexOutOfBoundsException exception) {
    exception.printStackTrace();
    break;
    case 3:
    if (Boolean.getBoolean(value.toString()) == false
    && getValueAt(row, 0) != null
    && getValueAt(row, 1) != null
    && getValueAt(row, 2) != null) {
    System.out.println("3. If - Added...");
    getSubjectsList()[row][3] = new Boolean(true);
    this.subjectListModel.addElement(this.subjectsList[row][0] +
    * new String(" - ") + this.subjectsList[row][2]);
    // subjectListModel.remove(row);
    fireTableCellUpdated(row, col);
    fireTableDataChanged();
    // this.doDeleteSubject();
    } else if (Boolean.getBoolean(value.toString()) ==
    true
    && getValueAt(row, 0) != null
    && getValueAt(row, 1) != null
    && getValueAt(row, 2) != null) {
    setValueAt("", row, col - 1);
    setValueAt("", row, col - 2);
    setValueAt("", row, col - 3);
    System.out.println("3. Else - Cleared...");
    // this.subjectListModel.remove(row);
    break;
    default:
    break;
    }// end switch
    getSubjectsList()[row][col] = value;
    fireTableCellUpdated(row, col);
    fireTableDataChanged();
    }// end if
    }// end
    * Function to enable edition for all the columns in the table
    * @param row --
    * the row that must be enabled.
    * @param col --
    * the col that must be enabled.
    * @return boolean -- indicate whether this cell is editble or
    not.
    public boolean isCellEditable(int row, int col) {
    if (row >= 0
    && (col >= 0 && col <= getNotEditable())) {
    return false;
    return true;
    * Function to get the column names for the model
    * @return Returns the columnNames.
    public String[] getColumnNames() {
    return this.columnNames;
    * Function to set the column names for the model
    * @param cols
    * The columnNames to set.
    public void setColumnNames(String[] cols) {
    // if the column names are null the default columns are used
    if (cols != null) {
    this.columnNames = cols;
    * Function to get the rows of subjects for the model
    * @return Returns the subjectsList.
    public Object[][] getSubjectsList() {
    if (this.subjectsList == null) {
    this.subjectsList = new
    Object[getTotalRows()][getColumnNames().length];
    return this.subjectsList;
    * Function to set the subjects list for the model
    * @param subjects
    * The subjectsList to set.
    public void setSubjectsList(Object[][] subjects) {
    // if the subject list is null create a new one
    // using default values
    if (subjects == null) {
    this.subjectsList = new
    Object[getTotalRows()][getColumnNames().length];
    return;
    this.subjectsList = subjects;
    * Function to get the total number of rows for the model. <b>NB:
    </b> This
    * is different to <code>
    getRowCount()</code>.<code>totalRows</code>
    * is the initial amount of rows that the model must have before
    data can be
    * added.
    * @return Returns the totalRows.
    * @see #setTotalRows(int)
    public int getTotalRows() {
    return this.totalRows;
    * Function to set the total rows for the model.
    * @param rows
    * The totalRows to set.
    * @see #getTotalRows()
    public void setTotalRows(int rows) {
    // if the rows are less than 0 the defaultRows are used
    // set getTotalRows
    if (rows > 0) {
    this.totalRows = rows;
    * Function to get the number of columns that is not editble
    * @return Returns the notEditable.
    public int getNotEditable() {
    return this.notEditable;
    * Function to set the number of columns that is not editable
    * @param notEdit The notEditable to set.
    public void setNotEditable(int notEdit) {
    if (notEdit < 0) {
    notEdit = 0;
    this.notEditable = notEdit;
    ----------------------------END TABLE MODEL----------------------------------

    I hope you don't expect us to read hundreds of lines of unformatted code? Use the "formatting tags" when you post.
    Why are you creating your own TableModel? It looks to me like the DefaultTableModel will store you data. Learn how to use JTable with its DefaultTableModel first. Then if you determine that DefaultTableModel doesn't provide the required functionality you can write your own model.

  • Table model and default model

    Hi All,
    can u tell me how to use table model or default table model. where i can references about it???
    thanks for all

    [http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#data]

  • 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

  • Copyig Data from a TABLE MODEL (TABLE) TO A FILE

    Hi guys,
    I wont to copy data from a Default Table Model to a File can someone write a pease of code that will do that for me.
    DefaultTableModel model = new DefaultTableModel();
    JTable table;
    public basic()
              super();
                  model.addColumn("Full Name");
                  model.addColumn("House No");
                  model.addColumn("Address");
                  model.addColumn("Town/County");
                  model.addColumn("Postcode");
                  model.addColumn("Telephone Number");
                  model.addColumn("Email Address");             
                  String[] socrates = { "Example", "33", "York RD", "Poole", "BH18 9RE", "01202776655", "[email protected]" };
                  model.addRow(socrates);
              /**This is the main setup for the Address Book
              *This has the main settings for the size, title
              *And main features of the Address book.
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.setSize(new Dimension(800, 600));
              this.setTitle("Large Print Address Book");
              this.setLayout(new FlowLayout ());
              //Main Application Parts
              JLabel welcome = new JLabel("Welcome to Thomas's Address Book v2.0.1");
              welcome.setFont(arial20);
              this.add(welcome);
              //Menu Bar
              JMenuBar mb = new JMenuBar();
              this.setJMenuBar(mb);
              //Table
              table = new JTable(model);
              this.add(table);
              JMenu fm = new JMenu("File");
              fm.setFont(arial20);
              mb.add(fm);
              //Menu Items          
              JMenuItem Add = new JMenuItem("Add Record");
              Add.setFont(arial20);
              Add.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e) 
                        addw a = new addw();                    
              fm.add(Add);
              //Import from a file
              JMenuItem inp = new JMenuItem("Import Records");
              inp.setFont(arial20);
              inp.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e) 
                        //Opens Import Window.
                        inportw i = new inportw();                    
              fm.add(inp);
              JMenuItem quit = new JMenuItem("Exit");
              quit.setFont(arial20);
              fm.add(quit);
              quit.addActionListener(this);
    class inportw extends JFrame
              //*Add Window Properties and Settings
              public inportw ()
                   this.setSize(new Dimension(400, 150));
                   this.setTitle("Inport Records");
                   this.setLayout(new FlowLayout ());
                   this.setVisible(true);
                   //Nmae
                   JLabel error_note = new JLabel("Error Here - Need to make table final!?");
                   error_note.setFont(arial20);
                   this.add(error_note);
                   //Add Button
                   JButton binport = new JButton("Inport");
                   binport.addActionListener(new ActionListener()
                        public void actionPerformed(ActionEvent e) 
                             ArrayList data = new ArrayList();          
                   this.add(binport);
         public void actionPerformed(ActionEvent e)
              System.out.println("Application Exit");
              System.exit(0);
         public static void main(String[] args)
              basic b = new basic();
              The information from the atable needs to go into a .txt file with each row on a new line. It also needs to be in the inport/export window that is in a class on its own when someone clicks export.
    A complete peace of code would be helpfull that would do this for me. Thankyou guys.

    Rite then,
    In answer to both post yes i have done my own homework if thats what you wont to call it.
    And to the second post yes i have put in a File to export to. the code has not be pasted on my origanal post.
    //Export Button - Export Window
                   JButton bexport = new JButton("Export (BUAB)");
                   bexport.addActionListener(new ActionListener()
                        public void actionPerformed(ActionEvent e) 
                             System.out.println("Export Pressed ");
                             try
                                 FileWriter file = new FileWriter("AddressData.txt");
                                BufferedWriter out = new BufferedWriter(file);
                                 out.write("AddressBook data File");
                                out.close();
                             catch (Exception ei)
                             System.err.println("Error: " + ei.getMessage());
                   this.add(bexport);This is the export button,
    I think the code for the table model should be something like this:
    I wont to do something like this
    model.getModel().getValueAt(0, 0);
    Arrylist data = new arrylist();
    try
                                 FileWriter ffile = new FileWriter("AddressData.txt");
                                BufferedWriter out = new BufferedWriter(file);
                                 out.write(data);
                                out.close();
                             catch (Exception ei)
                             System.err.println("Error: " + ei.getMessage());
                                 }          Im not 100% sure how to get the information from the model into the arrylist, though a loop.
    If there is a section of a webpage that may help could someone please post it for me.
    Unfortunatly for me Im visualy impaired and find some of this hard. I learn though looking at examples and creating my own programs that do something similar.
    If no one wonts to help then that fine with me !

Maybe you are looking for

  • Sales /Outgoing Excise Invoice number Range for J1IIN

    Dear Gurus, We are doing STO from excisable plant 1000 to plant 1100. We created a PO with document type UB ( STO) and created delivery with reference to PO and created billing document ( delivery challan). Against billing document number we created

  • AMD Radeon HD 6490M Windows 8 - 64-bit Driver

    Hi guys, I have HP Pavilion DV6-6B51EA and curently I'm using licenced Windows 7 Home Premium 64-bit. I tried upgrading to Windows 8 Release Preview but I can't install driver for my graphics card which is AMD Radeon HD 6490M. The problem is I can't

  • XI config for MM-SUS

    Hi, I am trying to configure XI for the MM-SUS scenario. I know there are predefined business scenarios available. I tried according to the configuration guide, but was not successful. Could anyone send me any document which describes any additional

  • IOS 5 Reminders Lists Bug?

    Howdy- I seem to be having a weird problem with my Reminders in iOS 5: In my Reminders Lists I see two groups labeled "On My iPhone" (see screenshot below). I can't seem to delete or merge these two lists into one.  My wife's iPhone 4S with iOS 5 doe

  • How do I get to Library/Internet Plug-In (Disabled) folder?

    How do I find the Library/Internet Plug-Ins (Disabled) folder?