Table model problem

I have a Jpanel in that there are two Jtables iam using same Table model for both tables.
when i entered text in one table and clik on second table the first table data showing in second table how to do this one

vitta wrote:
I have a Jpanel in that there are two Jtables iam using same Table model for both tables.and
vitta wrote:
i dont want to get the first table values reflected in the second tableIn all honesty how is the answer to this question not exceedingly obvious?

Similar Messages

  • 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

  • Calc problem with fact table measure used as part of bridge table model

    Hi all,
    I'm experiencing problems with the calculation of a fact table measure ever since I've used it as part of a calculation in a bridge table relationship.
    In a fact table, PROJECT_FACT, I had a column (PROJECT_COST) whose default aggregate was SUM. Whenever PROJECT_COST was used with any dimension, the proper aggregation was done at the proper levels. But, not any longer. One of the relationships PROJECT_FACT has is with a dimension, called PROJECT.
    PROJECT_FACT contains details of employees and each day they worked on a PROJECT_ID. So for a particular day, employee, Joe, might have a PROJECT_COST of $80 for PROJECT_ID 123, on the next day, Joe might have $40 in PROJECT_COST for the same project.
    Dimension table, PROJECT, contains details of the project.
    A new feature was added to the software - multiple customers can now be charged for a PROJECT, where as before, only one customer was charged.
    This percentage charge break-down is in a new table - PROJECT_BRIDGE. PROJECT_BRIDGE has the PROJECT_ID, CUSTOMER_ID, BILL_PCT. BILL_PCT will always add up to 1.
    So, the bridge table might look like...
    PROJECT_ID CUSTOMER_ID BILL_PCT
    123          100     .20
    123          200     .30
    123          300     .50
    456 400 1.00
    678 400 1.00
    Where for project 123, is a breakdown for multiple customers (.20, .30. .50).
    Let's say in PROJECT_FACT, if you were to sum up all PROJECT_COST for PROJECT_ID = 123, you get $1000.
    Here are the steps I followed:
    - In the Physical layer, PROJECT_FACT has a 1:M with PROJECT_BRIDGE as does PROJECT to PROJECT_BRIDGE (a 1:M).
    PROJECT_FACT ===> PROJECT_BRIDGE <=== PROJECT
    - In the Logical layer, PROJECT has a 1:M with PROJECT_FACT.
    PROJECT ===> PROJECT_FACT
    - The fact logical table source is mapped to the bridge table, PROJECT_BRIDGE, so now it has multiple tables it maps to (PROJECT_FACT & PROJECT_BRIDGE). They are set for an INNER join.
    - I created a calculation measure, MULT_CUST_COST, using physical columns, that calculates the sum of the PROJECT_COST X the percentage amount in the bridge table. It looks like: SUM(PROJECT_FACT.PROJECT_COST * PROJECT_BRIDGE.BILL_PCT)
    - I brought MULT_CUST_COST into the Presentation layer.
    We still want the old PROJECT_COST around until it get's phased out, so it's in the Presentation layer as well.
    Let's say I had a request with only PROJECT_ID, MULT_CUST_COST (the new calculation), and PROJECT_COST (the original). I'd expect:
    PROJECT_ID MULT_CUST_COST PROJECT_COST
    123          $1000     $1000
    I am getting this for MULT_CUST_COST, however, for PROJECT_COST, it's tripling the value (possibly because there are 3 percent amounts?)...
    PROJECT_ID MULT_CUST_COST PROJECT_COST
    123          $1000 (correct)      $3000 (incorrect, it's been tripled)
    If I were to look at the SQL, it would have:
              SELECT SUM(PROJECT_COST),
    SUM(PROJECT_FACT.PROJECT_COST * PROJECT_BRIDGE.BILL_PCT),
                   PROJECT_ID
              FROM ...
              GROUP BY PROJECT_ID
    PROJECT_COST used to work correctly before modeling a bridge table.
    Any ideas on what I did wrong?
    Thanks!

    Hi
    Phew, what a long question!
    If I understand correctly I think the problem lies with your old cost measure, or rather combining that with you new one in the same request. If you think about it, your query as explained above will bring back 3 rows from the database which is why your old cost measure is being multiplied. I suspect that if you took it out of the query, your bridge table would be working properly for the new measure alone?
    I would consider migrating your historic data into the bridge table model so that you have a single type of query. For the historic data each would have a single row in the bridge with a 1.0 BILL_PCT.
    Best of luck,
    Paul
    http://total-bi.com

  • Problem of custom table model

    Hi,
    i m leaning JTable recently, following is an experimental code which i wrote, it has a custom table model and custom tablecellrenderer, the custom tablecellrender determine the column of # of Years greater or equal than 5 should display color green, less than 5 should display color red, it works well, however, the custom table model should be smart enough to know that the # of Years column contains numbers (which should generally be right aligned and have a particular format), it also should know that the Vegetarian column contains boolean values, which can be represented by check boxes, but it didn't, i don't know why, i have implement a getColumnClass method,
    but it seems not work, have i make any mistakes? Any idea? Thanks
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.UIManager;
    import java.awt.Color;
    import java.util.Vector;
    public class CellRenderTestVector extends JFrame {
         protected JTable table;
         protected int width = 100;
         protected MyCustomTableModel model;
         public CellRenderTestVector() {
              JPanel pan0 = new JPanel(new BorderLayout());
              Container contentPane = getContentPane();
              pan0.setPreferredSize(new Dimension(500,200));
              model = new MyCustomTableModel();
              table = new JTable();
              table.setAutoCreateColumnsFromModel(false);
              table.setModel(model);
              table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                            TableColumn column = null;
              for (int i = 0; i < model.getColumnCount(); i++) {
                   DefaultTableCellRenderer renderer = new
                     ColoredTableCellRenderer();
                   column = new TableColumn(i,
                              width, renderer, null);
                              table.addColumn(column);
              TableColumn t_column = table.getColumnModel().getColumn(2);
              System.out.println(table.getColumnModel());
              JScrollPane scrollPane = new JScrollPane(table);
              pan0.add(scrollPane, BorderLayout.CENTER);
              contentPane.add(pan0);
                public class ColoredTableCellRenderer extends DefaultTableCellRenderer {
              public void setValue(Object value) {
                   Color  m_color;
                   Color GREEN = new Color(0, 128, 0);
                   Color RED = Color.red;
                   if (value instanceof Integer) {
                        Integer m_data = (Integer)value;
                        m_color = m_data.intValue() >= 5 ? GREEN : RED;
                                           setForeground(m_color);
                               setText(m_data.toString());
                   else {
                        super.setValue(value);
         public class Columndata {
              protected String m_title;
              public Columndata(String title) {
                   m_title = title;
         public class Rowdata {
              protected String fname;
              protected String lname;
              protected String sport_type;
              protected Integer no_year;
              protected Boolean vegetarian;
              public Rowdata(String fn, String ln,
                        String sp, int ny, boolean vg) {
                   fname = fn;
                   lname = ln;
                   sport_type = sp;
                   no_year = new Integer(ny);
                   vegetarian = new Boolean(vg);
         public class MyCustomTableModel extends AbstractTableModel {
              protected final Columndata m_column[] =
                        {new Columndata("First Name"),
                         new Columndata("Last Name"),
                         new Columndata("Sport"),
                         new Columndata("# of Years"),
                         new Columndata("Vegetarian")
              protected Vector m_vector;
              public MyCustomTableModel() {
                   m_vector = new Vector();
                   setDefaultData();
              public void setDefaultData() {
                   m_vector.removeAllElements();
                   m_vector.addElement(new Rowdata("Mary", "Campione",
                                                           "Snowboarding", 5, false));
                   m_vector.addElement(new Rowdata("Alison", "Huml",
                                                           "Rowing",3,true));
                   m_vector.addElement(new Rowdata("Kathy", "Walrath",
                                                           "Knitting",2, false));
                   m_vector.addElement(new Rowdata("Sharon", "Zakhour",
                                                           "Speed reading",20,true));
                   m_vector.addElement(new Rowdata("Philip", "Milne",
                                                           "Pool",10,false));
              public int getColumnCount() {
                   return m_column.length;
              public int getRowCount() {
                   return m_vector==null ? 0 : m_vector.size();
              public String getColumnName(int col) {
                   return m_column[col].m_title;
              public Object getValueAt(int nRow, int nCol) {
                   if (nRow < 0 || nRow>=getRowCount()) return "";
                   Rowdata row = (Rowdata)m_vector.elementAt(nRow);
                   switch (nCol) {
                   case 0: return row.fname;
                   case 1: return row.lname;
                   case 2: return row.sport_type;
                   case 3: return row.no_year;
                   case 4: return row.vegetarian;
                   return "";
              public Class getColumnClass(int c) {
                   return getValueAt(0, c).getClass();
         public static void createAndShowGUI() {
              try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              } catch (Exception evt) {}
                   JFrame f = new CellRenderTestVector();
                   f.setTitle("TableTest");
                   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   f.pack();
                 f.setVisible(true);
         public static void main(String[] args) {
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    You need to write your custom TableCellRenderes/Editors for each type. And don't forget to register your custom renderes via myTable.setDefaultRendere().

  • 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);
    }

  • A question about table model

    I created a table model and use JTable to display content of a database's table with that model.
    The problem is: when I update a data to data1 in a cell (first column) and hightlight another cell (second column), all cells of first column change content to data1. What 's the problem with my table model?
    import java.util.Vector;
    import java.sql.*;
    import javax.swing.table.AbstractTableModel;
    public class CommonTableModel extends AbstractTableModel {
    String[] columnNames;
    Vector          rows, newRow;
    ResultSetMetaData metaData;
    private boolean editable;
    public CommonTableModel(ResultSet rs, boolean editable) {
    this.editable = editable;
    try {
    metaData = rs.getMetaData();
    int numberOfColumns = metaData.getColumnCount();
    columnNames = new String[numberOfColumns];
    for(int column = 0; column < numberOfColumns; column++) {
    columnNames[column] = metaData.getColumnName(column+1);
    rows = new Vector();
    newRow = new Vector();
    while (rs.next()) {
    for (int i = 1; i <= getColumnCount(); i++) {
         newRow.addElement(rs.getObject(i));
    rows.addElement(newRow);
    } catch (SQLException ex) { System.err.println(ex);}
    public int getColumnCount() { return columnNames.length; }
    public int getRowCount() { return rows.size();}
    public String getColumnName(int column) { return columnNames[column];}
    public Object getValueAt(int row, int column) {
         newRow = (Vector)rows.elementAt(row);
         return newRow.elementAt(column);
    public Class getColumnClass(int column) {
         return getValueAt(0, column).getClass();
    public boolean isCellEditable(int row, int column) {
         if (column == 0) { return false; }
         return editable;
    public void setValueAt(Object value, int row, int column) {
         newRow = (Vector)(rows.elementAt(row));
         newRow.setElementAt(value, column);
         fireTableCellUpdated(row, column);
    }

    Try this :
    rows = new Vector();
    //newRow = new Vector();
    while (rs.next()) {
        newRow = new Vector(); // it must be here
        for (int i = 1; i <= getColumnCount(); i++) {
            newRow.addElement(rs.getObject(i));
        rows.addElement(newRow);
    }Denis

  • 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 with custom column model and table model not showing table header

    Hello,
    I am creating a JTable with a custom table model and a custom column model. However the table header is not being displayed (yes, it is in a JScrollPane). I've shrunk the problem down into a single compileable example:
    Thanks for your help.
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test1 extends JFrame
         public static void main(String args[])
              JTable table;
              TableColumnModel colModel=createTestColumnModel();
              TestTableModel tableModel=new TestTableModel();
              Test1 frame=new Test1();
              table=new JTable(tableModel, colModel);
              frame.getContentPane().add(new JScrollPane(table));
              frame.setSize(200,200);
              frame.setVisible(true);
         private static DefaultTableColumnModel createTestColumnModel()
              DefaultTableColumnModel columnModel=new DefaultTableColumnModel();
              columnModel.addColumn(new TableColumn(0));
              return columnModel;
         static class TestTableModel extends AbstractTableModel
              public int getColumnCount()
                   return 1;
              public Class<?> getColumnClass(int columnIndex)
                   return String.class;
              public String getColumnName(int column)
                   return "col";
              public int getRowCount()
                   return 1;
              public Object getValueAt(int row, int col)
                   return "test";
              public void setValueAt(Object aValue, int rowIndex, int columnIndex)
    }Edited by: 802416 on 14-Oct-2010 04:29
    added                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    Kleopatra wrote:
    jduprez wrote:
    See http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setHeaderValue(java.lang.Object)
    When the TableColumn is created, the default headerValue  is null
    So, the header ends up rendered as an empty label (probably of size 0 if the JTable computes its header size based on the renderer's preferred size).nitpicking (can't resist - the alternative is a cleanup round in some not so nice code I produced recently <g>):
    - it's not the JTable's business to compute its headers size (and it doesn't, the header's the culprit.) *> - the header should never come up with a zero (or near-to) height: even if there is no title shown, it's still needed as grab to resize/move the columns. So I would consider this sizing behaviour a bug.*
    - furthermore, the "really zero" height is a longstanding issue with MetalBorder.TableHeaderBorder (other LAFs size with the top/bottom of their default header cell border) which extends AbstractBorder incorrectly. That's easy to do because AbstractBorder itself is badly implemented
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459419
    Thanks for the opportunity to have some fun :-)
    JeanetteNo problem, thanks for the insight :)

  • JTable: Custom Table Model (pI)

    This is a follow-up to thread http://forum.java.sun.com/thread.jspa?threadID=725162 and thread http://forum.java.sun.com/thread.jspa?threadID=725158.
    As I'm hoping to have a table of 5 columns, where the 4th and 5th columns are for integer and float data types respectively, I am creating a custom table model under the assumption that I will not know beforehand the number of rows the table will contain.
    Problems? Having not specified the cell contents of the table, since it will be pupulated by users unknown to me, I did not declare or initialize a variable similar to TableDemo's data variable of type Object (see the TableDemo tutorial http://java.sun.com/docs/books/tutorial/uiswing/components/example-swing/TableDemo.java). As such, I am unable to specify the return parameters for the getRowCount() and getValueAt(~, ~) methods.
    To overcome this, I sought to replicate the example shown in TableDemo by doing the following:
    Object[][] cell = {"", "", "", new Integer(0), new Float(0.00f)};
    public int getRowCount()
      returncell.length;
    public Object getValueAt(int row, int column)
      return cell[row][column];
    //...I got the following errors:
    pathname\CustomTableModel.java:line #: incompatible types
    found: java.lang.String
    required: java.lang.Object[]
    and the errors continue...
    So I tried
    Object[] cell = {"", "", "", new Integer(0), new Float(0.00f)};
    // ...However, I got this error:
    C:\...\CustomTableModel.java:line #:array required, but java.lang.String found
    return cell[row][column];
    .......................... ^
    I just want to set the return parameters for getRowCount() and getValueAt(~,~) in the custom table model I'm creating. How do I do this?
    Cheers!
    PS Thanks for reading this far...

    I decided to use the DefaultTableModel, after all. I was using it before, but at the time, i didn't know that certain things I wanted to accomplish, it could too.
    Anyways, here's what I have been doing: http://forum.java.sun.com/thread.jspa?threadID=725861
    Thanks nonetheless for your help. And by the way, my client is adamant that I use a LinkedList, rather than a Vector for this project. But nevertheless, thanks.

  • JTable: Custom Table Model (pII)

    As was explained in pI, I'm creating a custom table model to overcome a few pitfalls I came across using the DefaultTableModel class, such as aligning cells, and getting certain columns to return only numeric type data. However, I've come upon a few roadblocks myself.
    How do I create each of the following methods:
    insertRow(int ow, int column)
    remove row(int row)
    addRow(Object[] rowData)Assuming that I decide to allow the user to add a column to the table, how would I create the methodaddColumn(Object columnName, Object[] columnData)And also, as I'm creating a custom table model, would I need to replicate DefaultTableModel's methods that inform the listeners that a change has been made to the table?
    Thanks!

    Thanks!
    I just got this response. Anyways, I found another solution that was, interestingly, from one of your threads written in 2005.
    This is what I did:
    // Letting the JTable know what each column stores and should return by
       // overloading the getColumnClass() method
       public Class getColumnClass(int column)
            if(recordsTable.getColumnName(column) == "Ranking")
              return Integer.class;
         /* Why do I keep ketting an IllegalArgumentException here? *
           * It keeps saying it cannot format given object as a Number */            
            else if(recordsTable.getColumnName(column) == "Price (�) ")
              return Float.class;
         else
           return getValueAt(0, column).getClass();         
       }However, another problem has arisen.
    The if method for the int column (Ranking column) works okay, and is even right-aligned. The else if arguments for the Price (�) column however is returning an IllegalArgumentException. This I just cannot figure out.
    Here's the code:package Practice;
      import java.awt.BorderLayout;
      import java.awt.Frame;
      import java.awt.Menu;
      import java.awt.MenuBar;
      import java.awt.MenuItem;
      import java.awt.MenuShortcut;
      import java.awt.event.ActionEvent;
      import java.awt.event.ActionListener;
      import java.awt.event.KeyEvent; // for MenuItem shortcuts
      import java.awt.event.WindowAdapter;
      import java.awt.event.WindowEvent;
      import java.awt.event.WindowListener;
      import javax.swing.JOptionPane;
      import javax.swing.JScrollPane; // JTable added to it, aiding flexibility
      import javax.swing.JTable; // The personally preferred GUI for this purpose
            // Provides a basic implementation of TableModel
      import javax.swing.table.DefaultTableModel;
              // This class uses Vector to store the rows and columns of data, though
              // programmer will be using LinkedLists
      import java.util.LinkedList;
      // User-defined classes
      import Practice.MusicDatabase;
      public class MusicBank extends Frame implements ActionListener
         MusicDatabase mDBase;
         Frame frame;
         String title = "",      // Frame's title
                file = "";           // pathname of the file to be opened
          // Declaring Menu and MenuItem variables
         Menu recordM; // ...
         // recordM
         MenuItem newRecordR_MI, deleteRecordR_MI;
         // Other irrelevant menus and sub items
        DefaultTableModel recordDetails;
        JTable recordsTable;
        LinkedList musicList;
        public MusicBank()
            musicList = new LinkedList();
            frame = new Frame(title);
            frame.setMenuBar(menuSystem());
            // Should user seek to close window externally
            frame.addWindowListener(new WindowAdapter()
                 public void windowClosing(WindowEvent we)
                     frame.dispose();
                     System.exit(0);
         recordDetails = new DefaultTableModel();
         // Creating the relevant columns
         recordDetails.addColumn("Title");
         recordDetails.addColumn("Identity");
         recordDetails.addColumn("Music Company");
         recordDetails.addColumn("Ranking");
         recordDetails.addColumn("Price (�) ");
         // Ensuring the table has at least one visible record (empty)
         recordDetails.addRow(populateRow("", "", "", 0, 0.00f));
         // Creating the table to display the data files (music record details)
         recordsTable = new JTable(recordDetails)
             // Letting the JTable know what each column stores and should return by
             // overloading the getColumnClass() method
            public Class getColumnClass(int column)
               if(recordsTable.getColumnName(column) == "Ranking")
                   return Integer.class;
                /* Why do I keep ketting an IllegalArgumentException here? *
                 * It keeps saying it cannot format given object as a Number */            
                else if(recordsTable.getColumnName(column) == "Price (�) ")
                    return Float.class;
                else
                    return getValueAt(0, column).getClass();         
      // Creating the menus
      public MenuBar menuSystem()
          MenuBar bar = new MenuBar();
          // Record menu and related items
          recordM = new Menu("Record");
          recordM.setShortcut(new MenuShortcut(KeyEvent.VK_R, false));        
          newRecordR_MI = new MenuItem("New record");
          newRecordR_MI.setShortcut(new MenuShortcut(KeyEvent.VK_N, false));
          deleteRecordR_MI = new MenuItem("Delete record");
          deleteRecordR_MI.setShortcut(new MenuShortcut(KeyEvent.VK_D, false));
           recordM.add(newRecordR_MI);
           recordM.addSeparator();
           recordM.add(deleteRecordR_MI);
            // Enabling menus with functionality
           newRecordR_MI.addActionListener(this);
           deleteRecordR_MI.addActionListener(this);
           // Adding menus and items to menu bar
           bar.add(recordM);
           return bar;        
      public void actionPerformed(ActionEvent ae)
          if(ae.getSource() == newRecordR_MI)
             newRecord();
          else if(ae.getSource() == deleteRecordR_MI)
             deleteRecord();       
      // Object that will be used, in conjunction with MusicDatabase's, to 
      // populate the JTable
      // A record in a JTable is equivalent to an element in a LinkedList
      public Object[] populateRow(String title, String name, String comp, int rank, float price)
          // First, update the LinkedList
          mDBase = new MusicDatabase(title, name, comp, rank, price);
          musicList.add(mDBase);
           // Then, update the table
           // As the parameters of Object tableDetails can only take a String or
           // object, rank and price will have to be cast as a String and later
           // parsed to their original form before use.
           String rankPT = ""+rank, pricePT = ""+price;        
           Object rowDetails[] = {title, name, comp, rankPT, pricePT};
           return rowDetails;
      public static void main(String args[])
          MusicBank app = new MusicBank();
           // Using the platform's L&F (if Win32,  Windows L&F; Mac OS, Mac OS L&F,
           // Sun, CDE/Motif L&F)
           // For more on this, refer to the WinHelp Java tutorial by F. Allimont
           try
               UIManager.getSystemLookAndFeelClassName();
           catch(Exception e)
               JOptionPane.showMessageDialog(app,
                    "Failed to create the Windows Look and Feel for this program",
                    "Look and Feel (L&F) error",
                    JOptionPane.ERROR_MESSAGE);
           app.frame.setSize(500, 500);
           app.frame.setVisible(true);
            // Placing frame in the centre of the screen on-loading
           app.frame.setLocationRelativeTo(null);
      // action methods per menu items
      // Also, why do I keep getting an ArrayIndexOutOfBoundsException
      // here? I do know what this exception is, and how it works, but just cannot
      // understand what is causing it
      public void newRecord()
          // Before adding a new record, check if previous record has complete
          // entries. If not, either display a message (JOptionPane) or disallow
          // request (simply do nothing)        
          // Proceed based on assesment
          if(queryState() == true)
              // Inform user that all entries need to be filled in before a new
              // record can be created
              JOptionPane.showMessageDialog(this, // current frame
                       "There are incomplete cells in the table."+
                       "\nPlease fill these in before proceeding",       // Message to user
                       "Incomplete entries",                                // Title
                       JOptionPane.ERROR_MESSAGE);                           // Relevant icon
          else
               // To ensure that both the linked list & the table are simultaneously
               // updated, JOptionPane's input dialogs are used to temporarily store
               // the data which is then inputted into both (linked list and JTable)
              String titleN, identityN, companyN; int rankN; float priceN;
              titleN = JOptionPane.showInputDialog(this, "Enter song title");
              identityN = JOptionPane.showInputDialog(this,                                      "Enter name of singer/band");
             companyN = JOptionPane.showInputDialog(this,                                 "Enter signed/unsigned company");
             rankN = Integer.parseInt( JOptionPane.showInputDialog(this,
                             "Enter rank (a number)") );
            System.out.println("\n JTable rows = "+recordDetails.getRowCount());
             // Ensuring that the chosen rank is not already entered
             /* Problem lies here */
             for(int row = 1; row <= recordDetails.getRowCount(); ++row)
                 if((recordDetails.getValueAt(row, 4)).equals(""+rankN))
                     rankN = Integer.parseInt( JOptionPane.showInputDialog(this,
                             "That number's already chosen.\nPlease enter a rank ") );
             priceN = Float.parseFloat( JOptionPane.showInputDialog(this,                                 "Finally, enter price �") );
             mDBase = new MusicDatabase(titleN, identityN, companyN, rankN, priceN);
             musicList.add(mDBase);
             recordDetails.addRow(populateRow(titleN, identityN, companyN, rankN,
         priceN));
             System.out.println("JTable rows after creation = "+
                   recordDetails.getRowCount());
         // Enabling the delete record menu item (as necessary)
         if((recordsTable.getRowCount()) > 0)
              deleteRecordR_MI.setEnabled(true);
      } // newRecord()
      public void deleteRecord()
         int selectedRow = recordsTable.getSelectedRow();
         recordDetails.removeRow(selectedRow);
          // Removing the element from the LinkedList's corresponding index
          musicList.remove(selectedRow);
          System.out.println("Existing rows = "+recordsTable.getRowCount());
           // If there are no more rows, disallow user from trying to delete rows
           if(selectedRow <= 0)
              deleteRecordR_MI.setEnabled(false);
      } // deleteRecord()
      // Method to query if all cells have changed their states (empty or not)
      public boolean queryState()
          // Obtaining number of rows
          int rows = recordDetails.getRowCount();
          int columns = recordDetails.getColumnCount();
          boolean isEmpty = false; // cell
          System.out.println("Rows = "+rows);
          System.out.println("Columns = "+columns);
          try{
              // Assessing all cells for complete entries
              // This approach is flexible, rather than hardcoding the rows available,
              // making it more reusable (assuming it will always be 5 columns)
              for (int rowIndex = 0; rowIndex<=rows; ++rowIndex)
                  if((recordDetails.getValueAt(rowIndex, 1)).equals(""))
                 isEmpty = true;
                  else if((recordDetails.getValueAt(rowIndex, 2)).equals(""))
               isEmpty = true;
                  else if((recordDetails.getValueAt(rowIndex, 3)).equals(""))
               isEmpty = true;                
                  else if((recordDetails.getValueAt(rowIndex, 4)).equals("0"))
               isEmpty = true;
                  else if((recordDetails.getValueAt(rowIndex, 5)).equals("0.00"))
               isEmpty = true;
          catch(Exception e)
             System.out.println(e.getMessage());
          return isEmpty;
      Now here is the code for the MusicDatabase class
    package Practice;
    class MusicDatabase
        private String songTitle, identity, musicCompany;
        private int rank;
        private float priceF;
        // Defining the constructor
        public MusicDatabase(String title, String name, String company,                                int rankingInt, float price)
           songTitle = title;
           identity = name;
           musicCompany = company;
           rank = rankingInt;
           priceF = price;
        } // constructor
       // Other methods
    } // class MusicDatabaseSorry, but am not sure if these codes are executable, as where I am (a general library), JVM is not on the machine I am using. (Remember, i don't have ready acess to the Internet, so I could not use my machine, nor the facilities that had the JVM - unavailable to me at the time).
    Thanks!
    Reformer...
    PS I do hope the code pasted was not too much. Kind regards....

  • Custom table model won't cast

    Hi, I have a JTable with a custom table model that extends AbstractTableModel. I want to take the number of a selected table row and pass it to a method of my custom model to get back the original complex object represented by the row.
    int x = mytable.getSelectedRow();
    MyTableModel model = (MyTableModel)(mytable.getModel());
    MyOwnClass orig = model.myConversionMethod(x);
    Problem: when I call mytable.getModel() then cast it to my custom model class (so I can call this conversion method) I get a ClassCastException.
    What am I doing wrong? Thanks in advance for any help/advice you can give.
    Mike

    Where is the table model created?Right after the JTable is created, I call...
    mytable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    mytable.setModel(new SortFilterModel(new MyTableModel()));

  • Memory leak when refreshing table models

    Hi,
    I have a memory leak in a GUI app, and i have traced the problem down to some JTables I have which display data from a database (I used Netbeans profiler to look at the number of objects created for different classes, and there are a large number of classes like com.mysql.jdbc.ResultSet, com.mysql.jdbc.Statement, com.mysql.jdbc.Field[] accumulating, aswell as lots of byte[] and char[] arrays). The allocation stack traces for these objects seem to point to my table models where I do a lot of database lookups to create the model.
    Every time I am refreshing the tables, the Heap Space increases by a few MegaBytes, and a load of objects get created and retained. After refreshing the tables a number of times, the heap eventually gets filled and I get OutOfMemory error.
    The problem is I don't understand how this is happening - when the tables are refreshed, the code I use is something like this:
    setModel(new MyTableModel());
    So theoretically each time I refresh, the old model should be garbage collected (because setting the new model means there are no references to the old model), but I get the feeling that all the models are accumulating in the heap and not being collected. I dont understand why this could be - I was wondering if anyone had any ideas? (PS My table models dont use any static fields)
    Cheers,
    james

    Hi JacobsB,
    The reason I'm setting new models (which I dont normally do) is that each time the table is refreshed, the number and type of columns may change. Since altering the column model is quite complicated (there is no convenient removeColumn() method of any of the standard model classes) and involves messing around with the column model, which ends up screwing up the whole model (e.g. column renderers, column count, column class etc.) I decided it was actually easier to just create a new model instead! Is there a way to alter the column structure another way?
    later,
    James

  • Some error in setting table model to a JTable..kindly help..

    hi all,
    i m pasting a code of a function in which i fetch data from the database n display it in a JTable pasted on a panel in a JFrame window.
    There is some problem with the table model which i m unable to correct.
    Kindly help..
    public void showDetails(){
         Statement statement;
         ResultSet rs;
    Connection connection;
         //DATABASE CONNECTION
              try{
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              connection=DriverManager.getConnection("jdbc:odbc:iirsdb");
                   statement=connection.createStatement();
                   String strQuery=null;
                   Object[][] data;
                   //SELECT QUERIES
                        if(index>=1 && index<=14)
                             strQuery="select IP_Address,"+strMapped+",Timestamp from tblStatic where IP_Address='" + strIP + "' and Timestamp='"+strTime+"' and "+strMapped+"='"+strDetailResult+"'";
                        if(index>17 && index<=22)
                             strQuery="select IP_Address,"+strMapped+",Timestamp from tblSemiDyn where IP_Address='" + strIP + "' and Timestamp='"+strTime+"' and "+strMapped+"='"+strDetailResult+"'";
                        if(index==25)
                             strQuery="select IP_Address,"+strMapped+",Timestamp from tblDyn where IP_Address='" + strIP + "' and Timestamp='"+strTime+"' and "+strMapped+"='"+strDetailResult+"'";
                   rs=statement.executeQuery(strQuery);
                   ResultSetMetaData rsmd=rs.getMetaData();
                   int col=rsmd.getColumnCount();
                   Vector colNames=new Vector();
                   Vector row=new Vector();
                   for(int i=1;i<=col;i++){
                        colNames.addElement(rsmd.getColumnName(i));
                   while(rs.next()){
                        for(int i=1;i<=col;i++){
                             row.addElement(rs.getObject(i));
                        data.addElement(row);
                   DefaultTableModel tableModel = new DefaultTableModel(data, colNames);
                   JTable table= new JTable(tableModel);
                   //table.setModel(new DefaultTableModel(data,colNames));
                   //JTable.revalidate();
                   //display table with ResultSet contents
                             //JTable table= new JTable(row, colNames);
                             JScrollPane scroller=new JScrollPane(table);
                             pnlFifth.add(scroller,BorderLayout.CENTER);
                             scroller.setVisible(true);
                             scroller.validate();
                   rs.close();
    }catch(ClassNotFoundException cnfex){
                   System.err.println("Failed to load JDBC/ODBC driver");
                   cnfex.printStackTrace();
    catch (SQLException sql){
    JOptionPane.showMessageDialog(this, "Cannot connect to Database"+sql,"Error", JOptionPane.WARNING_MESSAGE);
    }

    hi..okays..will take care of this..actually, this ws d first time i ws using this community service.
    Below.i inserted checkstatements but still d table isnt getting displayed..wht to do? D logic is correct i guess but whr is d problem?
    public void showDetails(){
         Statement statement;
         ResultSet rs;
        Connection connection;
        Vector colNames=null;
             Vector data=null;
         //DATABASE CONNECTION
              try{
                    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                    connection=DriverManager.getConnection("jdbc:odbc:iirsdb");
                   String strQuery=null;
              data = new Vector();
                   //SELECT QUERIES
                        if(index>=1 && index<=14)
                             strQuery="select IP_Address,"+strMapped+",Timestamp from tblStatic where IP_Address='" + strIP + "' and Timestamp='"+strTime+"' and "+strMapped+"='"+strDetailResult+"'";
                        if(index>17 && index<=22)
                             strQuery="select IP_Address,"+strMapped+",Timestamp from tblSemiDyn where IP_Address='" + strIP + "' and Timestamp='"+strTime+"' and "+strMapped+"='"+strDetailResult+"'";
                        if(index==25)
                             strQuery="select IP_Address,"+strMapped+",Timestamp from tblDyn where IP_Address='" + strIP + "' and Timestamp='"+strTime+"' and "+strMapped+"='"+strDetailResult+"'";
                   statement=connection.createStatement();
                   rs=statement.executeQuery(strQuery);
                   ResultSetMetaData rsmd=rs.getMetaData();
                   int col=rsmd.getColumnCount();
                   //int r=rsmd.getRowCount();
                   colNames=new Vector();
                   for(int i=1;i<=col;i++){
                        colNames.addElement(rsmd.getColumnName(i));
                   while(rs.next()){
                        Vector row=new Vector(col);
                        for(int i=1;i<=col;i++){
                             row.addElement(rs.getObject(i));
                        data.addElement(row);
                   rs.close();
                   statement.close();
    }catch(ClassNotFoundException cnfex){
                   System.err.println("Failed to load JDBC/ODBC driver");
                   cnfex.printStackTrace();
    catch (SQLException sql){
                JOptionPane.showMessageDialog(this, "Cannot connect to Database"+sql,"Error", JOptionPane.WARNING_MESSAGE);
    JTable table=new JTable(data,colNames)
                public Class getColumnClass(int column)
                    for (int row = 0; row < getRowCount(); row++)
                        Object o = getValueAt(row, column);
                        if (o != null)
                            return o.getClass();
                    return Object.class;
            JScrollPane scrollPane = new JScrollPane( table );
            //getContentPane().add( scrollPane );
            pnlFifth.add( scrollPane );
            scrollPane.setVisible(true);
    }     

  • 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

  • "Cannot set null table model"

    How do I get rid of the pop-up error msg when
    clicking on an EJB (in the System Window of
    a writable Project file):
    "Cannot set null table model"

    This error usually occurs when a compilation error is blocking creation of a valid EJB model, the data object that supports the EJB class editor.
    Try re-compiling the project to see if that identifies the problem.

Maybe you are looking for