JTable and the ****** TableModel

Ok, I know I'm messing with all of these threads about table and table model but there is no way for me to understand:
I do
MyTable table = new MyTable( rowData, column );
public class MyTable extends JTabel {
MyTableModel myMod = null;
public MyTable( Vector vec1, Vector vec2 ) {
super();
myMod = new MyModel( vec1, vec2 );
setModel( myMod);
public class MyModel extends DefaultTableModel {
public MyModel( Vector vec1, Vector vec2 ) { super(vec1,vec2); }
but my tables are empty (1)
and I can't add rows (2)
Why? I'm messing with this for a lot.. could some one very kind post a bit of code that make me understand what is right and what is not right?
thanks in advance

Try this out, and you will probably figure out what you're doing wrong.
* TableRenderDemo.java is a 1.4 application that requires no other files.
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
* TableRenderDemo is just like TableDemo, except that it
* explicitly initializes column sizes and it uses a combo box
* as an editor for the Sport column.
public class TableRenderDemo extends JPanel {
    private boolean DEBUG = false;
    public TableRenderDemo() {
        super(new GridLayout(1,0));
        JTable table = new JTable(new MyTableModel());
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);
        //Set up column sizes.
        initColumnSizes(table);
        //Fiddle with the Sport column's cell editors/renderers.
        setUpSportColumn(table, table.getColumnModel().getColumn(2));
        //Add the scroll pane to this panel.
        add(scrollPane);
     * This method picks good column sizes.
     * If all column heads are wider than the column's cells'
     * contents, then you can just use column.sizeWidthToFit().
    private void initColumnSizes(JTable table) {
        MyTableModel model = (MyTableModel)table.getModel();
        TableColumn column = null;
        Component comp = null;
        int headerWidth = 0;
        int cellWidth = 0;
        Object[] longValues = model.longValues;
        TableCellRenderer headerRenderer =
            table.getTableHeader().getDefaultRenderer();
        for (int i = 0; i < 5; i++) {
            column = table.getColumnModel().getColumn(i);
            comp = headerRenderer.getTableCellRendererComponent(
                                 null, column.getHeaderValue(),
                                 false, false, 0, 0);
            headerWidth = comp.getPreferredSize().width;
            comp = table.getDefaultRenderer(model.getColumnClass(i)).
                             getTableCellRendererComponent(
                                 table, longValues,
false, false, 0, i);
cellWidth = comp.getPreferredSize().width;
if (DEBUG) {
System.out.println("Initializing width of column "
+ i + ". "
+ "headerWidth = " + headerWidth
+ "; cellWidth = " + cellWidth);
//XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
public void setUpSportColumn(JTable table,
TableColumn sportColumn) {
//Set up the editor for the sport cells.
JComboBox comboBox = new JComboBox();
comboBox.addItem("Snowboarding");
comboBox.addItem("Rowing");
comboBox.addItem("Knitting");
comboBox.addItem("Speed reading");
comboBox.addItem("Pool");
comboBox.addItem("None of the above");
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
//Set up tool tips for the sport cells.
DefaultTableCellRenderer renderer =
new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
sportColumn.setCellRenderer(renderer);
class MyTableModel extends AbstractTableModel {
private String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
private Object[][] data = {
{"Mary", "Campione",
"Snowboarding", new Integer(5), new Boolean(false)},
{"Alison", "Huml",
"Rowing", new Integer(3), new Boolean(true)},
{"Kathy", "Walrath",
"Knitting", new Integer(2), new Boolean(false)},
{"Sharon", "Zakhour",
"Speed reading", new Integer(20), new Boolean(true)},
{"Philip", "Milne",
"Pool", new Integer(10), new Boolean(false)}
public final Object[] longValues = {"Sharon", "Campione",
"None of the above",
new Integer(20), Boolean.TRUE};
public int getColumnCount() {
return columnNames.length;
public int getRowCount() {
return data.length;
public String getColumnName(int col) {
return columnNames[col];
public Object getValueAt(int row, int col) {
return data[row][col];
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
* Don't need to implement this method unless your table's
* editable.
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
* Don't need to implement this method unless your table's
* data can change.
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
data[row][col] = value;
fireTableCellUpdated(row, col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
System.out.println();
System.out.println("--------------------------");
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("TableRenderDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
TableRenderDemo newContentPane = new TableRenderDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
Good luck!!

Similar Messages

  • JTable and ResultSet TableModel with big resultset

    Hi, I have a question about JTable and a ResultSet TableModel.
    I have to develop a swing JTable application that gets the data from a ResultSetTableModel where the user can update the jtable data.
    The problem is the following:
    the JTable have to contain the whole data of the source database table. Currently I have defined a
    a TYPE_SCROLL_SENSITIVE & CONCUR_UPDATABLE statement.
    The problem is that when I execute the query the whole ResultSet is "downloaded" on the client side application (my jtable) and I could receive (with big resultsets) an "out of memory error"...
    I have investigate about the possibility of load (in the client side) only a small subset of the resultset but with no luck. In the maling lists I see that the only way to load the resultset incrementally is to define a forward only resultset with autocommit off, and using setFetchSize(...). But this solution doesn't solve my problem because if the user scrolls the entire table, the whole resultset will be downloaded...
    In my opinion, there is only one solution:
    - create a small JTable "cache structure" and update the structure with "remote calls" to the server ...
    in other words I have to define on the server side a "servlet environment" that queries the database, creates the resultset and gives to the jtable only the data subsets that it needs... (alternatively I could define an RMI client/server distribuited applications...)
    This is my solution, somebody can help me?
    Are there others solutions for my problem?
    Thanks in advance,
    Stefano

    The database table currently is about 80000 rows but the next year will be 200000 and so on ...
    I know that excel has this limit but my JTable have to display more data than a simple excel work sheet.
    I explain in more detail my solution:
    whith a distribuited TableModel the whole tablemodel data are on the server side and not on the client (jtable).
    The local JTable TableModel gets the values from a local (limited, 1000rows for example) structure, and when the user scroll up and down the jtable the TableModel updates this structure...
    For example: initially the local JTable structure contains the rows from 0 to 1000;
    the user scroll down, when the cell 800 (for example) have to be displayed the method:
    getValueAt(800,...)
    is called.
    This method will update the table structure. Now, for example, the table structure will contain data for example from row 500 to row 1500 (the data from 0 to 499 are deleted)
    In this way the local table model dimension will be indipendent from the real database table dimension ...
    I hope that my solution is more clear now...
    under these conditions the only solutions that can work have to implement a local tablemodel with limited dimension...
    Another solution without servlet and rmi that I have found is the following:
    update the local limited tablemodel structure quering the database server with select .... limit ... offset
    but, the select ... limit ... offset is very dangerous when the offset is high because the database server have to do a sequential scan of all previuous records ...
    with servlet (or RMI) solution instead, the entire resultset is on the server and I have only to request the data from the current resultset from row N to row N+1000 without no queries...
    Thanks

  • JTable and filtering

    Hi,
    is it possible to filter data in a JTable? For example, if the user only wants to view data that contains "TOM" in the firstname column, then only rows with TOM will be displayed on the table.
    How can implement that? Would I need different tablemodels for different user's selections?

    Yes, it is possible. I've actually used two methods. In the first (and most complex), I built another (filter) jtable which contained field, operator, operand values for each field(column) in my other (data) jtable. The data jtable was actually populated from a SQL table which contained values which were not in the (data) jtable. The rows from the (filter) jtable were saved to the database and a stored procedure parsed it to create a query while was run against the data, which populated the (filter) jtable. The rows were joined by 'and'. They now want me to change this into a full blown query tool ((col1 > 14 or col1<3) and (col2=6 or col2=8)). EEK!
    In the second, I had a predefined filter (i.e. somecolumn > 14) which was turned on & off via a checkbox. In this one, I passed a vector to the tablemodel and the tablemodel built another vector which was used to display.
    Hope this helps.

  • How do I scroll a JTable as the selection cursor moves out-of-view?

    If a row is selected in a JTable, and the user navigates up and down using arrow keys, as the selection moves out of view, the table automatically scrolls. In my app, I am programmatically selecting rows, but if the selection is out of view, the table does not scroll. does anyone know how to achieve this? I know I could examine the position of the selected row etc. and scroll the view myself, but this seems clunky. Ideally, I would fire off KeyEvents to get the behaviour for free, but I can't see where to fire them to

    I know I could examine the position of the selected row etc. and scroll the view myselfWhy? Thats what the methods where designed for (assuming you are talking about the scrollRectToVisible(...) method).
    Ideally, I would fire off KeyEvents to get the behaviour for free,That seems clunky to me.
    When you use KeyEvents its a cause / effect relationship. That is first you use a KeyEvent to change selection. Then then if the table is at the bottom it scroll one row. So in you program if you on on row 5 and you want to select row 30, you would need to invoke 25 KeyEvents. Seems pointless to me unless you have special logice that processes every row as it gets selected.
    If you want to persue this route then you can just invoke the default actions for the up/ down/ left/ right keys. This posting should give you an idea of how to do this:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=657819

  • The TableModel.getColumnClass() always return String class

    Hi, anybody here has ever encountered and problem like mine? Please help if you do.
    I have an JTable and the table model derived from AbstractTableModel, I use TableSorter from the tutorial to sort the table(I have also implemented my own sorting method, but the result is the same), but whatever the data type of the table column, the getColumnClass() method always return String type, so the table is always sorted by String type.
    My implementation of this method is as following:
    return getValueAt(0, columnIndex).getClass();
    What is possibly wrong?
    Please help, thank you so much!
    Janet

    Presumably the data in your first cell is a String object... therefore your code in getColumnClass() will always return String.class.

  • JTable - Swapping the Rows and Columns

    This issue was raised in the Java Programming forum. Received initially as a weird requirement, it now seems that it is more common than you might think. Under it's original title it was "JTable - Limitation or Not?"
    I introduced the topic here so that the thread perspective can include more experienced Swing developers.
    The JTable in it's default layout is intended to hold database tables with records in rows. But what if you want records in columns?
    Some have said why? Just accept the row layout. Others have said use a customised form. Both reasonable views. Despite this, others report that the inherrited power of the JTable is worth leveraging and they have been doing it for years. Albeit with messy code in certain cases.
    This is a clear candidate for a popular derived component. If the existing JTable were renamed as a JTableRecordPerRow I am describing a JTableRecordPerColumn. The corresponding Table Model must naturally have a getRowClass method and no getColumnClass method.
    Java is good at seperating data from display issues so essentially this is only a display issue. The data representation is unaffected.
    While this may be so, the TableModel for a JTable makes the link from the display to the data so it must have knowledge about cell type to trigger the correct cell editor for example.
    I think it is fair to say that the standard JTable has not be designed with alternative row/column or column/row displays in mind. Hence a single getColumnClass method. However implementing a Table model which exchanges columns for rows is a good start. This leaves a few loose ends where editting is concerned.
    While this may not be an ideal topic for anyone just learning Swing I have been encouraged to consider the general case within the limitations of the cell types normally supported by the default Table model.
    I would have a guess that this is an established component in many private Java libraries already.
    Views and experience on this topic extremely welcome.

    It appears to me that while interchanging the rows and columns of a JTable is not trivial it is still worthwhile as a workhorse component.
    Perhaps the original design could have allowed for an aternative layout manager of somekind but this could easily have made description of records/rows and fields/columns confusing.
    I will probably get this summary wrong but I aill attempt to collate the neatest approach as I see it. Criticisms or shorter steps welcome. My thanks to the original contributors traceable from this thread.
    In the descriptions below a distinction is made between the normal internal data model representation of a row, called "mrow", and the displayed form "row".
    Only the TableModel need be changed.
    1 Use row 0 to show the headers by a)disabling the normal TableHeader renderer b)setting the cell renderer for column 0 to the default renderer used by the TableHeader and c)using the getValueAt method to return mcol header values for the row entries.
    2 For other row, col values to getValueAt return the value at mcol, mrow where mcol==row-1 & mrow==col.
    3 Create a new getCellClass(col,row) method to return the class where mrow==0 and mcol==row-1. Note that I am only trying to immitate the common use of of a database record per mrow here.
    4 Override a)getCellRenderer and b)getCellEditor to use getCellClass
    Four steps with seven parts seems worth it to me.
    The power of Swing!
    Many thanks to all.

  • Is it possible to print JTable and custom JPanel on the same page?

    Hello everybody!
    I have a custom panel extending JPanel and implementing Printable.
    I am using paint() method to draw some graphics on it's content pane. I would like to print it, but first I would like to add a JTable at the bottom of my panel. Printing just the panel goes well. No problems with that.
    I was also able to add a JTable to the bottom of JFrame, which contains my panel.
    But how can I print those two components on one page?

    Hi, thanks for your answer, but I thought about that earlier and that doesn't work as well... or mybe I'm doing something wrong. Here is the sample code:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.print.PageFormat;
    import java.awt.print.Printable;
    import java.awt.print.PrinterException;
    import java.awt.print.PrinterJob;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    public class ReportFrame extends JFrame implements Printable {
         private static final long serialVersionUID = -8291124097290245799L;
         private MyPanel rp;
         private JTable reportTable;
         private HashPrintRequestAttributeSet attributes;
         public ReportFrame() {
              rp = new MyPanel();
              String[] columnNames = { "Column1", "Column2", "Column3" };
              String[][] values = { { "Value1", "Value2", "Value3" }, { "Value4", "Value5", "Value6" }, { "Value7", "Value8", "Value9" } };
              reportTable = new JTable(values, columnNames);
              add(rp, BorderLayout.CENTER);
              add(reportTable, BorderLayout.SOUTH);
              setTitle("Printing example");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setPreferredSize(new Dimension(700, 700));
              pack();
              setVisible(true);
         @Override
         public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
              if (pageIndex >= 1)
                   return Printable.NO_SUCH_PAGE;
              Graphics2D g2D = (Graphics2D) graphics;
              g2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
              return Printable.PAGE_EXISTS;
         public static void main(String[] args) {
              new ReportFrame().printer();
         class MyPanel extends JPanel implements Printable {
              private static final long serialVersionUID = -2214177603101440610L;
              @Override
              public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
                   if (pageIndex >= 1)
                        return Printable.NO_SUCH_PAGE;
                   Graphics2D g2D = (Graphics2D) graphics;
                   g2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
                   return Printable.PAGE_EXISTS;
              @Override
              public void paint(Graphics g) {
                   super.paintComponent(g);
                   Graphics2D g2D = (Graphics2D) g;
                   int x = 0, y = 0, width = 70, height = 70;
                   for (int i = 0; i < 50; i++) {
                        g2D.drawOval(x + i * 10, y + i * 10, width, height);
         public void printer() {
              try {
                   attributes = new HashPrintRequestAttributeSet();
                   PrinterJob job = PrinterJob.getPrinterJob();
                   job.setPrintable(this);
                   if (job.printDialog(attributes))
                        job.print(attributes);
              } catch (PrinterException e) {
                   JOptionPane.showMessageDialog(this, e);
    }UPDATE:
    I've managed to get this to work, by calling 2 methods inside the outer frame's print method (lines 78 and 79)
    Those two methods are:
    rp.paint(g2D);
    reportTable.paint(g2D);but still it is not the way I would like it to be.
    First of all both the ReportPanel and ReportTable graphics are printed with the upper-left corner located in the upper-left corner of the JFrame and the first one is covering the second.
    Secondly, I would like to rather implemet the robust JTable's print method somehow, because it has some neat features like multipage printing, headers & footers. But I have no idea how to add my own graphics to the JTables print method, so they will appear above the JTable. Maybe someone knows the answer?
    Thanks a lot
    UPDATE2:
    I was googling nearly all day in search of an answer, but with no success. I don't think it's possible to print JTable using it's print() method together with other components, so I will have to think of something else i guess...
    Edited by: Adalbert23 on Nov 22, 2007 2:49 PM

  • Hiding a column while keeping the data in the TableModel

    Hello
    I am reading data in from a database and I add the data from the resultSet to
    a vector of vectors.
    e.g my table
    user_id | user_fname | user_lname | prj_id | prj_name
    I am reading in the above information but I dont want to
    display the id fields i.e
    the user_id and
    the prj_id fields
    to the user but I need to keep them in the vector inside my tablemodel
    for futher database manipulation.
    I've looked at threads saying to set the width of the column to 0 is this the best way???
    Could someone please share with me a way to do the above.
    Thank you very much

    Figure out how to call the removeColumn method on your JTable. Calling the method only removes the column viewed (JTable), not the actual column in the (DefaultTable) Model.
    If you go for the proposed "do it so small it cant be seen" solution, you have to "lock" the colum width so users can't do it bigger manually with the mouse...

  • Two JTables using the same RowSorter

    Ok, I have the following situation:
    package testing;
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    public class Testing
         public static void main(String args[])
              JFrame frame = new JFrame("SplitPaneTest");
              String[] columnNames =
                        {"First Name",     "Last Name",     "Sport",               "# of Years",          "Vegetarian",           "#",     "A Number"};
              Object[][] data =
                      {{"Mary",      "Campione",      "Snowboarding",      new Integer(5),      new Boolean(false),     "1",      new Float(37.1)},
                       {"Alison",    "Huml",            "Rowing",                new Integer(3),      new Boolean(true),     "2",      new Float(324.76)},
                       {"Kathy",     "Walrath",           "Knitting",           new Integer(2),      new Boolean(false),     "4",      new Float(6)},
                       {"Sharon",    "Zakhour",           "Speed reading",      new Integer(20),      new Boolean(true),     "3",      new Float(4567)},
                       {"Philip",      "Milne",           "Pool",                new Integer(10),      new Boolean(false),     "5",      new Float(1337)},};
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              JTable leftTable      = new JTable(model);
              JTable rightTable      = new JTable(model);
              leftTable.removeColumn(leftTable.getColumnModel().getColumn(6));
              leftTable.removeColumn(leftTable.getColumnModel().getColumn(5));
              rightTable.removeColumn(rightTable.getColumnModel().getColumn(4));
              rightTable.removeColumn(rightTable.getColumnModel().getColumn(3));
              rightTable.removeColumn(rightTable.getColumnModel().getColumn(2));
              rightTable.removeColumn(rightTable.getColumnModel().getColumn(1));
              rightTable.removeColumn(rightTable.getColumnModel().getColumn(0));
              leftTable.setAutoCreateRowSorter(true);
              rightTable.setAutoCreateRowSorter(true);
              JScrollPane leftScrollPane = new JScrollPane(leftTable);
              JScrollPane rightScrollPane = new JScrollPane(rightTable);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setLayout(new GridLayout(1, 2));
              frame.add(leftScrollPane);
              frame.add(rightScrollPane);
              frame.setVisible(true);
              frame.pack();
    }Basically what I want to do is when the user sorts either one of the tables, I want the adjacent table to sort as well according to the column of the clicked table. Also, on an unrelated note, does anyone know of a more efficient means of setting the models of the table so I don't have to remove the unwanted columns:
              leftTable.removeColumn(leftTable.getColumnModel().getColumn(6));
              leftTable.removeColumn(leftTable.getColumnModel().getColumn(5));
              rightTable.removeColumn(rightTable.getColumnModel().getColumn(4));
              rightTable.removeColumn(rightTable.getColumnModel().getColumn(3));
              rightTable.removeColumn(rightTable.getColumnModel().getColumn(2));
              rightTable.removeColumn(rightTable.getColumnModel().getColumn(1));
              rightTable.removeColumn(rightTable.getColumnModel().getColumn(0));Thank you for your time,
    Brandon

    Thanks for the comment and the link. It seemed to work with OP's SSCCE when I tested it, maybe there isn't a problem when both tables also share the same TableModel?
    db (busy with some office work now and no time to run any further tests)

  • JTable and large CSV files

    I have been looking for a clear answer (with source code) to a problem commonly asked in the forums. The question is "how do I display a large comma delimited (CSV) file in a JTable without encountering a Java heap space error?" One solution is described at http://forum.java.sun.com/thread.jspa?forumID=57&threadID=741313 but no source code is provided. Can anyone provide some example code as to how this solution works? It is not clear to me how the getValueAt(r, c) method can be used to get the (r+1)th row if only r rows are in the TableModel. I greatly appreciate any help.

    Perhaps if I posted my code, I might get a little help. First, my class that extends abstract table model
    public class DataTableModel extends AbstractTableModel{
         private static final long serialVersionUID = 1L;
         Object[][] data;
         DataColumnFormat[] colFormat;
         int nrows, ncols, totalRows;
         public DataTableModel(Object[][] aData, DataColumnFormat[] aColFormat, int aTotalNumberOfRows){
              data=aData;
              colFormat=aColFormat;
              nrows=data.length;
              ncols=data[0].length;
    //          number of rows in entire data file.
    //          This will be larger than nrows if data file has more than 1000 rows
              totalRows=aTotalNumberOfRows;
         public int getRowCount(){
              return nrows;
         public int getColumnCount(){
              return ncols;
         public String getColumnName(int aColumnIndex){
              return colFormat[aColumnIndex].getName();
         public Object getValueAt(int r, int c){
              if(colFormat[c].isDouble()){
                   return data[r][c];
              return data[r][c];
         public boolean isCellEditable(int nRow, int nCol){
              return true;
         @SuppressWarnings("unchecked")
         public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
         protected void updateData(){
    //          replace values in data[][] object with new rows from large data file
    }Suppose data = new Object[1000][100] but my CSV file has 5000000000 lines (to exaggerate). By my understanding getValueAt(r, c) could not go beyond r=1000 and c=100. So, how would I update data with the next 1000 lines by way of the getValueAt(r,c) method? Moreover, how would I implement this so that the table appears to scroll continuously? I know someone has a solution to this problem. Thanks.

  • Not firing setValueAt() in the TableModel

    Hi All,
    I have a JTabbedPane which contains 6 Tabs and each Tab contains a JTable. A table may have JTextFieldcelleditor , JCheckBoxcelleditor...
    I entered a value in the JTextFieldcelleditor of first Tab.
    and immediately ...I am changing from first Tab to second Tab, then entered value is not set with the TableModel i,.e setValueAt() of My TableModel is not firing...
    Regards,
    Ananth

    set
    yourtable.putClientProperty("terminateEditOnFocusLost",
                             Boolean.TRUE);for all tables and the values are set when changing tabs.
    EDIT: :shakefist: @ mac ! ;-)

  • BC4J: Split TableData to JTable and JTextPane - possible? - how

    Hi all,
    I got a table with some columns, but 2 of them can contain more than 1000 characters. So I want the content of these 2 columns displayed in 2 JTextpanes, which then contain always the content of theses to columns when a row is selected.
    My question now is:
    How can I get them into the JTextPanes and is there a chance/method to get the primary key of a row when the row which is selected?
    I also have to question how to hide a column, because I want to hide the primary key but only hide and how to change the header of the jTable.
    I tried:
    tableEmpView1.getColumn("Empno").setHeaderValue("Employee Number");
    tableEmpView1.getColumnModel( ).removeColumn(tableEmpView1.getColumn("Job"));
    But the don't work in my application!
    I can remove the colum with this call but then I also removed it from the tablemodel, so I have no chance to get the content of the "hiddeN" column after that and the oder method-call doesn't work, although there is no compiler error or runtime error there is no headerValue changed.
    Anyone any Idea about my question?
    Thanks
    Peter Zerwes

    Hi all,
    I got a table with some columns, but 2 of them can contain more than 1000 characters. So I want the content of these 2 columns displayed in 2 JTextpanes, which then contain always the content of theses to columns when a row is selected.
    My question now is:
    How can I get them into the JTextPanes and is there a chance/method to get the primary key of a row when the row which is selected?There are two questions here. One is how to display some attribute from a row in JTable in another control, such that only the current row value is displayed in the other control. You simply need to drop the other control in the UI editor and bind it to the same ViewObject and desired attribute. Framework will coordinate the passing of value from the current row into that attribute. See OTN sample "JClient Binding demo" - how it handles the display of Image control in a pane with JTable (Image for current Item from JTable is displayed in ImageControl). The sample is at:
    http://otn.oracle.com/sample_code/products/jdev/jclient/jclient_binding_demo.html
    The second question is how to get the primary key of the row which is selected.
    Call panelBinding.findIterBinding(<your iterator name>).getCurrentRow();
    I also have to question how to hide a column, because I want to hide the primary key but only hide and how to change the header of the jTable.
    I tried:
    tableEmpView1.getColumn("Empno").setHeaderValue("Employee Number");
    tableEmpView1.getColumnModel( ).removeColumn(tableEmpView1.getColumn("Job"));
    But the don't work in my application!
    I can remove the colum with this call but then I also removed it from the tablemodel, so I have no chance to get the content of the "hiddeN" column after that and the oder method-call doesn't work, although there is no compiler error or runtime error there is no headerValue changed.
    Anyone any Idea about my question?TO hide a column from display, you may either not select that column in the JTable binding or provide a control-hint "display=hide" in the ViewAttribute editor on the desired ViewObject attribute in your BC4J project.
    To change Table headers, etc see OTN how to at
    http://otn.oracle.com/products/jdev/howtos/JClient/jclient_jtable.html
    Thanks
    Peter Zerwes

  • JTable and integers

    I have a tablemodel that holds the headers and the amount of rows and then inputted into a Jtable.what im trying to do is gather information in certain columns(ie integers) and add them up with the end result displaying the total at the end of the column.i have tried calling the column but i havent had luck so far.Ive also tried creating a 2d array instead of the tablemodel but no luck

    i cannot input anything into my JTable when ur code is put into it. I think its because the tablemodel is (headers,35) so there are no values to start with in each row.
    Ive tried alternating ur code to make it add floats in a column but still no luck.
    public void BS()
           String[] headers = new String[]{"Assets", "", "Liabilities", "", "Owner's Equity", ""};
            DefaultTableModel model = new DefaultTableModel(headers,35);
            model.addTableModelListener(this);
            bstable = new JTable( model )
                   //  Returning the Class of each column will allow different
                   //  renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
                   //  The Cost is not editable
                   public boolean isCellEditable(int row, int column)
                        int modelColumn = convertColumnIndexToModel( column );
                        return (modelColumn == 3) ? false : true;
            bstable.getTableHeader().setReorderingAllowed(false);
            bsscrollpane = new JScrollPane(bstable);
            bsscrollpane.setViewportView(bstable);
        public void tableChanged(TableModelEvent e)
              System.out.println(e.getSource());
              if (e.getType() == TableModelEvent.UPDATE)
                   int row = e.getFirstRow();
                   int column = e.getColumn();
                   if (column == 1)
                        TableModel model = bstable.getModel();
                                    Float     assets = ((Float)model.getValueAt(row, 1)).floatValue();
                        Float value = new Float(assets);
                        model.setValueAt(value, row, 1);
         }I dont know if the calculate column will work. Do i have to loop it so it keeps on adding the rows in the 1st column.?

  • Multiple JTables for One TableModel

    i have 3 tabs, and 5 tables, they arent that big mind you...the biggest table is about 150rows, 10cols, and the rest are about 10-20rows, 15cols
    they update every 5 secs, so i create a new datavector and set the tables model to the new data vector, every time
    this probably isnt the best way to do it :P
    the thing is, the last 4 table's data depends on the first (big) table's data, what is the best way to have multiple jtables displaying different data from the same data source, this way i just have to create and update the main datavector once while the other 4 just change their views
    take advantage of MVC alittle better...
    thanks

    Here is a simple [url http://forum.java.sun.com/thread.jsp?forum=31&thread=411506]example of a TableModel being shared by two tables.
    After you update the main data vector you would need to fireTableDataChanged(...); This should cause all views to be updated.

  • Jtable and reload of data

    Hello, I've a JTable with some buttons in some columns.
    First I create some data and a custom model with this data and the table with this model.
    Then for the "special" buttons colums I use the getColumModel and setCellRenderer and setCellEditor to set the way of paint and a custom editor,finally i set up a mouse listener to the table.
    Everything works but, when I delete one of the rows, I make new data[][] and get model of the table and use the method model.reload(data)
    After updating the screen, the line with the deleted row dissapear, the table adjust his size automatically, everything works but there is a last blank line... and when I click where it was supposed to be the buttons (and there are no line here) the listener works (where there is no row) and obviusly an error appear.
    The problems seem that model.reload(data) with the new data correctly repaint the table, but the last size is not deleted and there is a last blank row, and the listeners of this line are not removed from the model...
    Any idea of what can I do?
    Thanks in advance.

    Read the AbstractTableModel API. Notice all the fireXXX methods. Somewhere in your custom TableModel you need to fire the appropriate event to tell the table that the model has changed and then it will repaint itself as required.

Maybe you are looking for