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.?

Similar Messages

  • JTable and clipboard...

    Hi all!
    I'm trying to copy data from JTable to system clipboard. Here's my code that is
    supposed to do that except it doesn't work. Nothing happens. The system is
    Windows, rigth click invokes menu with only one position - COPY, which is served
    by a appopriate ActionListener. I want to copy entire table (all data):
    private class NotEditableTable extends JTable
    NotEditableTable(Object[][] data, Object[] columnNames)
    super(data, columnNames);
    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    setCellSelectionEnabled(true);
    getTableHeader().setReorderingAllowed(false);
    NotEditableTableEngine nete = new NotEditableTableEngine();
    this.addMouseListener(nete);
    public boolean isCellEditable(int row, int column)
    return false;
    private class NotEditableTableEngine extends MouseAdapter implements ActionListener
    public void mouseReleased(MouseEvent e)
    if (e.isPopupTrigger())
    JPopupMenu menu = new JPopupMenu();
    JMenuItem menuitem = new JMenuItem(Lang.TABLE_COPY, new ImageIcon("res/Copy16.gif"));
    menuitem.addActionListener(this);
    menu.add(menuitem);
    menu.show(NotEditableTable.this, e.getX(), e.getY());
    public void actionPerformed(ActionEvent e)
    TransferHandler th = new TransferHandler(null);
    NotEditableTable.this.setTransferHandler(th);
    Clipboard clip = NotEditableTable.this.getToolkit().getSystemClipboard();
    th.exportToClipboard(NotEditableTable.this, clip, TransferHandler.COPY);
    }

    I also tried the code above with a simple JTextField, both with text selected and not.Did my sample code use the TransferHandler??? The simple way to do it for a JTextField would be
    Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
    StringSelection testData = new StringSelection( textField.getText );
    //StringSelection testData = new StringSelection( textField.getSelectedText );
    c.setContents(testData, testData);
    As for the table I said that the Ctrl-C KeyStroke will invoke the default Action to copy selected data from the JTable to the Clipboard. This can be tested manually by simply using Ctrl-C. If you want to invoke it in your program then you need to get the corresponding Action from the JTable and invoke the ActionPerformed method of the Action. You can try using the
    getActionForKeyStroke(...) method of JComponent to get the Action.

  • 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

  • JTables and frequency count report

    Is it possible to use jTable and make the cells un-editable and have it set up where if you click on a cell it could perform a specific action? I�m working on a program that calculates a frequency count report and I want to be able to click on the cell and have it display in another window the observations that contributed to that cells count. Is this possible using jTable or is there a better way to get what I want? Thanks for any suggestions.

    Yes, it looks to me as if it should be possible.

  • Help needed with doubles and integers

    I just want to start telling all you that you have been a big help to me the last couple of months. Now, for my issue. I'm having a problem doing some work with doubles and integers. Below is the code I've tried. But, I keep getting mismatch types. I need num3 to fill in a JTextField by the end with the answer for the calc. Num2 is fill in from a JTextField with a double.
    Int num1 = 0, num4 = 0, num3 = 0;
    double num2 = 0, totint = 0;
    for(count = 0; num4 < count; count++)
    totint = (1 + num2);
    System.out.println(totint);
    num3 = double (num1 * totint);
    String k = Integer.toString(num3);
    tf3.setText(k); (This is a JTextField)
    Test data
    num1 = 10000
    num2 = 3.4
    num4 = 4
    num3 = the value from the calc

    First of all, your for loop is never going to run.
    for (count = 0; num4<count; count++)
    totint = (1 + num2);
    System.out.println(totint);
    num4 = 4 and will not be less than count, so the for loop will not be executed.
    Second, what exactly are you trying to accomplish here. The way you have your code set up, the for loop (if it were to execute) would print out 4.4 each time it passes, then do the calculation. You may need to rethink your objective.

  • Jtable and database

    hi,
    i am using jdevlopper 10g and oracle 10g express.
    i create a database and a new connection to it.
    in the first frame, i created a new jtable and i want that it containts data from the database.
    is any one can help me.
    thanks

    Hi,
    you have two options:
    - Use ADF and ADF Swing, in which cae the database connect is through a business service (e.g. ADF Business Components or EJB)
    - Create a JDBC connection to the database and populate the JTable model with the data (which is cumbersome). You find tutorials on the web of how to do this.
    Frank

  • JTable and events

    Hi,
    I am fairly new to Swing. I don't understand the following behaviour of JTables. If I minimize the frame containing the JTable, and afterwards maximize it again, the getValuAt method is called again for all visible rows and columns, even if the table data did not change. The same happens whit a mousemove over the JTable, and if another screen is dragged over the screen and afterwards dragged away from the screen.
    It is possible this is normal, but it affects the performance of the application in a quite considerable way.
    Greetings,
    Marc

    StansislavL is right, when the JTable is repainted also the data needs to be repainted and therefor retrieved form the DataModel. The way to solve your performance issues is to read the data once into a Vector of beans and use this to retrieve the value's for your JTable, like:public Object getValueAt (int row, int col)
      SomeBean sb = (SomeBean) data.get(row) //data = Vector of beans
      switch (col)
        case 0: return sb.getID();
        case 1: return sb.getName();
      return null;
    }greetz,
    Stijn

  • JTable and cell color

    Hello, hope you can help me here -
    I have a JTable, and based on the value of a certain column in a row, I want the background color of that entire row to change to a different color. How can I perform this operation?
    I have tried to override JTable's prepareRenderer, but it doesn't seem to be working.
    Any clues?
    Thanks!
    -Kirk

    Hi.
    First of all. Try searching the forum there have been plenty of posts on this subject.
    Now to answer your question of how to set the color. The trick lies in the cellrenderer.
    A JTabel contains several models internally. If I'm not mistaking the ColumnModel contains the appropriate rendere for every column. The simplest thing to do in my opinion is to use a decorator pattern on the TableCellRenderer interface. Something along the likes of this.
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    public class ColorTableCellRenderer implements TableCellRenderer {
    private TableCellRenderer render;
    public ColorTableCellRenderer( TableCellRenderer render ){
    this.render = render;
    * @see javax.swing.table.TableCellRenderer#getTableCellRendererComponent(javax.swing.JTable, java.lang.Object,
    * boolean, boolean, int, int)
    public Component getTableCellRendererComponent( JTable table , Object value , boolean isSelected , boolean hasFocus ,
    int row , int column ) {
    if( table != null ){ //Replace with specific condition
    Component cmp = this.render.getTableCellRendererComponent( table , value , isSelected , hasFocus , row , column );
    cmp.setBackground( Color.cyan );
    //Maybe need to call a validate or setOpaque. if experiencing problems.
    return cmp;
    }else{
    return this.render.getTableCellRendererComponent( table , value , isSelected , hasFocus , row , column );
    After that the easiest to do is set the defaultCellrenderer of your table in the following fashion.
    table.setDefaultRenderer(Object.class, new ColorTableCellRenderer( table.getDefaultRenderer(Object.class) ));
    Or this should also work.
    table.getColumnModel().getColumn(0).setCellRenderer(new ColorTableCellRenderer(chosenRenderer));
    Hope this helps & Good luck!

  • Help with TableRowSorter , JTable and JList

    Hello,
    I�m developing an application in which I�m using a Jtable and Jlist to display data from a database. Jtable and Jlist share the same model.
    public class DBSharedModel extends DefaultListModel implements TableModelFor the Jtable I set a sorter and an filter
    DBSharedModel dataModel = new DBSharedModel();
    Jtable jTable = new JTable(dataModel) ;
    jTable.createDefaultColumnsFromModel();
    jTable.setRowSelectionAllowed(true);
    TableRowSorter<DBSharedModel> sorter = new TableRowSorter <DBSharedModel> (dataModel);
    jTable.setRowSorter(sorter);From what I read until now JavaSE 6 has NOT a sorter for JList (like one for JTable).
    So, I am using one from a this article http://java.sun.com/developer/technicalArticles/J2SE/Desktop/sorted_jlist/index.html
    When I sort the data from the table, I need to sort the data from the list, too.
    My ideea is to make the Jlist an Observer for the Jtable.
    My questions are:
    1.     How can I find if the sorter makes an ASCENDING or DESCENDING ordering?
    2.     How can I find what the column that is ordered?
    Or if you have any idea on how can I do the ordering on Jlist to be simultaneous to Jtable .
    Please help!
    Thank you

    Oh what the hell:
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java. This one has been getting a lot of very positive comments lately.

  • JScrollPanel, JTable, and a HorizontalScrollBars

    Am creating a JScrollPane, a JTable, and adding the table to the pane.
    I am also creating MyTableMode which extends AbstractTabelModel. MyTableModel provides the interface between the JTable and my particular data. I am able to display and edit the data, that interface is working fine.
    When I have more than about 10 rows of data, the vertical scroll bars appear. This is what I expect.
    But if there are more columns than can be seen in the viewport, the horizontal scroll bars do not appear. This is not what I expect.
    Example: if I create table with 72 rows by 72 columns, only rows 1-10 and columns 1-40 are visible (based on dialog size, preferred size, etc.). The vertical scroll bars are present, but the horizontal scroll bars are not. The user will not be able to scroll the viewport and see columns 41-72.
    I've read (and re-read) the "How to use Tables" and "How to use Scrollpanes", tutorials, and do not see anything obvious. Probably missed something. I did notice that none of the table examples have horizontal scrioll bars.
    Any suggestions?

    It's one of those days. Here is code with the imports:
    package components;
    * TableDemo.java requires no other files.
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    * TableDemo is just like SimpleTableDemo, except that it
    * uses a custom TableModel.
    public class TableDemo extends JPanel {
        private boolean DEBUG = false;
        public TableDemo() {
            super(new GridLayout(1,0));
            JTable table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            table.setFillsViewportHeight(true);
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            add(scrollPane);
        class MyTableModel extends AbstractTableModel {
            public int getColumnCount() {
                //return columnNames.length;
                return 72;
            public int getRowCount() {
                //return data.length;
                return 72;
            public String getColumnName(int col) {
                //return columnNames[col];
                return Integer.toString(col);
            public Object getValueAt(int row, int col) {
                //return data[row][col];
                return 0;
            public boolean isCellEditable(int row, int col) {
                return false;
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("TableDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            TableDemo newContentPane = new TableDemo();
            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();
    }

  • Problem with JTable and JPanel

    Hi,
    I'm having problems with a JTable in a JPanel. The code is basicly as follows:
    public class mainFrame extends JFrame
            public mainFrame()
                    //A menu is implemeted giving rise to the following actions:
                    public void actionPerformed(ActionEvent evt)
                            String arg = evt.getActionCommand();
                            if(arg.equals("Sit1"))
                            //cells, columnNames are initiated correctly
                            JTable table = new JTable(cells,columnNames);
                            JPanel holdingPanel = new JPanel();
                            holdingPanel.setLayout( new BorderLayout() );
                            JScrollPane scrollPane = new JScrollPane(holdingPanel);
                            holdingPanel.setBackground(Color.white);
                            holdingPanel.add(table,BorderLayout.CENTER);
                            add(scrollPane, "Center");
                            if(arg.equals("Sit2"))
                                    if(scrollPane !=null)
                                            remove(scrollPane);validate();System.out.println("ScrollPane");
                                    if(holdingPanel !=null)
                                            remove(holdingPanel);
                                    if(table !=null)
                                            remove(table);table.setVisible(false);System.out.println("table");
                            //Put other things on the holdingPanel....
            private JScrollPane scrollPane;
            private JPanel holdingPanel;
            private JTable table;
    }The problem is that the table isn't removed. When you choose another situation ( say Sit2), at first the table apparently is gone, but when you press with the mouse in the area it appeared earlier, it appears again. How do I succesfully remove the table from the panel? Removing the panel doesn't seem to be enough. Help is much appreciated...
    Best regards
    Schwartz

    If you reuse the panel and scroll pane throughout the application,
    instantiate them in the constructor, not in an often-called event
    handler. In the event handler, you only do add/remove of the table
    on to the panel. You can't remove the table from the container
    which does not directly contain it.
    if (arg.equals("Sit2")){
      holdingPanel.remove(table);
      holdingPanel.revalidate();
      holdingPanel.repaint(); //sometimes necessary
    }

  • 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

  • Reading strings and integers from a text file

    I want to read the contents of a text file and print them to screen, but am having problems reading integers. The file contains employee's personal info and basically looks like this:
    Warren Laing
    32 //age, data type is int
    M //gender, data type is String
    Sharon Smith
    44
    F
    Here's what I've done so far. The method should continue reading the file until there's no lines left. When I call it from main, I get a numberFormatException error. I'm not sure why because the data types of the set and get methods are correct, the right packages have been imported, and I'm sure I've used Integer.parseInt() correctly (if not, pls let me know). Can anyone suggest why I'm getting errors, or where my code is going wrong?
    many thanks
    Chris
    public void readFile() throws IOException{
    BufferedReader read = new BufferedReader(new FileReader("personal.txt"));
    int age = 0;
    String input = "";
    input = read.readLine();
    while (input != null){
    setName(input);
    age = Integer.parseInt(input);
    setAge(age);
    input = read.readLine();
    setGender(input);
    System.out.println("Name: " + getName() + " Age: " + getAge() + " Gender: " + getGender());
    read.close();

    To answer your question - I'm teaching myself java and I haven't covered enumeration classes yet.
    With the setGender("Q") scenario, the data in the text file has already been validated by other methods before being written to the file. Anyway I worked out my problems were caused by "input = read.readLine()" being in the wrong places. The code below works fine though I've left out the set and get methods for the time being.
    Chris
    public static void readFile()throws IOException{
    String name = "";
    String gender = "";
    int age = 0;
    BufferedReader read = new BufferedReader(new FileReader("myfile.txt"));
    String input = read.readLine();
    while(input != null){
    name = input;
    input = read.readLine();
    gender = input;
    input = read.readLine();
    age = Integer.parseInt(input);
    input = read.readLine();
    System.out.println("Name: " + name + " Gender: " + gender + " Age: " + age);
    read.close();

  • 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.

  • JScroller on JTable and table size

    Hi everyone...
    I have a small problem...i added JScrollPane to my JTable...but if i do the following...
    JScrollPane contentScroller= new JScrollPane(myJTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    myJTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);In this case scroller works great....accept if i have a smaller data set to show...for example only one column...
    Basically what i would like is to be able to set like minimum size of my JTable...is that possible...

    Oh ya...
    sorry i apologize...
    Well basically what i did is the following...
    In the constructor of my sub-class that extends JTable i set the following property:
    this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    /*...........................................................................*/ And then i also added the following code...(i created some additional methods...i dont really know if this is the right way but i didnt find anything more suitable for my problem)
    /*i set JScrollPane onto witch i added my JTable class instance, to a private JscrollPane variable*/
    public void setParentJPanel(JScrollPane parentJScrollPane){
            this.parentJScrollPane = parentJScrollPane;
    /*I only added these 3 methods cos i wanted to get the size of JScrollPane onto witch i added my JTable class instance*/
        public JScrollPane getParentJPanel(){
            return this.parentJScrollPane;
    /*this methods sort of sets all the columns to equal size witch i guess i wanted it to do...*/
        public void setAllColumnsWidth(){
            int parentWidth = this.getParentJPanel().getWidth();
            int columnNumber = this.getColumnNumber();/*method that i wrote to work with another class that works with database*/
            int columnWidth = parentWidth/columnNumber;
            for(int i=0;i < columnNumber;i++)
                this.getColumnModel().getColumn(i).setPreferredWidth(columnWidth);     
        }Hmmm sorry again for not posting my solution...its not really that much impressive thats why i didnt post it the first time...
    Well i hope it helps....(what i needed is basically how to set columns to as equal size as possible...)

Maybe you are looking for

  • BW reports from CRM web gui

    Hello Experts, We are displaying two web reports from BW in CRM layout. For this our requirement is not to have a separate account created for each CRM user in BW. Just to have one generic user created in BW and the same generic user has to be used a

  • How to change my Macbook Pro's mane on the network ?

    Hi all, I trust your all well ! Could you please help me ? I want to change my Macbook Pro's mane on the network, I mean when I check all the computers using the network, I always find mine named with its IP or "MACBOOKPRO-1FQC" and I would like to c

  • Is it possible to share only a part of contact.

    Hi, Is it possible to share only a part of an contact? For example: If you have more nubmers and data for one contact (mostly we do) and would like to send someone only one number and not the rest of contact`s data (personal)? I know that on some oth

  • How to configure 2 external monitors with X1 Carbon

    I have a brand new X1 Carbon (Generation 1 3444-CYU), and I also have the docking station.  My intention is to be able to have the laptop cover closed, and to use the power switch on the top of the docking station to start (apply power to) the laptop

  • HELP! MY AIRPORT EXPRESS KEEPS RESTARTING ITSELF????

    SO, I had this baby for a while now, maybe since novemberish and it was working great until the inevitable happens... Airport utility won't detect my airport express device at all and i've tried everything! All my airport express does is turn amber f