ArrayList Population in JTable

I have a jtable built using AbstractTableModel. I want to populate the tabe using an arraylist but do not know how to go about it. I know I need to override public Object getValueAt(int row, int column) method.
Can anyone guide me on this?

Have a look at Rob Camick's [Row TableModel |http://tips4java.wordpress.com/2008/11/21/row-table-model].
And his other Model classes too.
Have a look at [this thread|http://forums.sun.com/thread.jspa?forumID=57&threadID=5373299] for design considerations.
Jerome
P.S.: note that unless you use a handy subclass such as Rob's ones, you'd have to override the getValueAt(int row, int column) method and all the other abstract methods of AbstractTableModel (check the Javadoc).
P.P.S.: more seriously, have a look at the API Javadoc in general, most often it pays back.
Edited by: jduprez on Nov 19, 2009 1:05 PM

Similar Messages

  • POPULATING THE JTABLE FROM DATABASE!!I need find out where im going wrong?

    for some reason wen i run the program the fields dont populate!!! no errors in my output monitor nothing? im puzzled! no errors in the code either!!! im using Netbeans IDE 6.0 with no code generators watsoever! i type out all type code myself! i have checked and rechecked and rechecked! been stuck here for two days! if anyone has code out there they are willing to share or possibly advice if u've had the same problem please let me know where to look or pass on the solution!
    Hurry Im losing a lot of hair!!!!!!
    Edited by: Dubs08 on Feb 7, 2008 10:36 PM

    code ?

  • JTable question regarding Index/ID's from a VB guy

    Greets!
    So i am coming from VB6 where i use an ActiveX object table to display data from a SQL database table. When populating the table i include the 'ID' field from the database table as a hidden column. So when a user selects a row, i pull the hidden column's ID# and use that to do whatever (bring up another edit form, etc)
    So here i am in Java now, i've been playing with jTable for a while now and seem to be getting the hang of the basics, but when i replicated the above scenario, hiding the ID column had weird results (cursor would dissappear when i scroll over with the arrow keys). I also saw another post where another person said that along with populating the jTable i should also have an array that stores the ID that matches the RowIndex from the jTable itself.
    This is the table model that i am using:
    public class jTableModel extends AbstractTableModel {
        private double xTotal;
        private int colnum;
        private int rownum;
        private String[] colNames;
        private  ArrayList<Object[]> ResultSets;
        private Icon zIcon;
        /** Creates a new instance of FoodTableModel */
        public jTableModel(ResultSet rs,frmMain frm) {
          ResultSets=new ArrayList<Object[]>(); 
          Icon icon1 = new ImageIcon(getClass().getResource("/main/images/bullet_ball_glass_blue.png"));
          Icon icon2 = new ImageIcon(getClass().getResource("/main/images/bullet_ball_glass_red.png"));
          Icon icon3 = new ImageIcon(getClass().getResource("/main/images/bullet_ball_glass_green.png"));
          try{
            while(rs.next()){
                switch (rs.getInt("Type")) {
                    case 1: zIcon = icon1; break;
                    case 2: zIcon = icon2; break;
                    case 3: zIcon = icon3; break;
                Object[] row={zIcon,rs.getString("Name"),rs.getString("Description"),rs.getString("ID")};
                ResultSets.add(row);
            String[] zNames={
                "","Name","Description","ID"
            colNames = zNames;
            colnum=4;
          catch(Exception e){
              System.out.println("(jTableModel: There was an error: " + e);
        public Object getValueAt(int rowindex, int columnindex) {
           Object[] row=ResultSets.get(rowindex);
           return row[columnindex];
        public int getRowCount() {
            return ResultSets.size();
        public int getColumnCount() {
            return colnum;
        @Override
        public String getColumnName(int param) {
           return colNames[param];
        public double getTotal() {
            return xTotal;
        @Override
        public Class getColumnClass(int column) {
         return getValueAt(0, column).getClass();
        }Can anyone give me any tips in this area or point me in the right direction?
    Any help would be appreciated.

    Dear Poster,
    As no response has been provided to the thread in some time I must assume the issue is resolved, if the question is still valid please create a new thread rephrasing the query and providing as much data as possible to promote response from the community.
    Best Regards,
    SDN SRM Moderation Team

  • Trying to populate a JTable

    Hello
    Im having some issues populating a JTable.
    I know that one of the ways to populate it is using the constructor JTable(Object[][] rowData, Object[] columnNames)
    All the exmples I�ve seen on the net initialize the arrays this way
    private String[] columnNames = {"","First Name","Last Name","Email"};
    private Object[][] rowData = {
    {"Mary", "Campione","Snowboarding", new Boolean(false)},
    {"Alison", "Huml","Rowing", new Boolean(true)},
    {"Kathy", "Walrath","Knitting", new Boolean(false)} };
    that works fine, the problem is that Im trying to display more that 8000 records from a Database
    and I can�t initialize the data array that way so I created a loop that pupulates the array and here is where the issue starts
    One of the Colums needs to be a checkbox, and I know that in order to display the check box I need to store a boolean value into the Object array (data)
    however if I do the following i get an error message
    Object data[][] = new Object[rows][cols];
    data[row][col] = new Boolean(false);
    with the above code I get an ArrayStoreException which I know what It means, whowever how come when I initialze the array the first way it works
    and the second way doesn�t work ?
    Can someone helps?
    Thanks

    Don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting.
    the problem is that Im trying to display more that 8000 records from a DatabaseWell you shouldn't be using an array in this case because you don't know how many rows are in the database. You should be using Vectors. You can search the forum for my "Table From Database" (without the spaces) example posted in the forum.

  • Clicking JButton in JTable

    Hello all,
    I have populated a JTable with Buttons and need for them to appear to be clicked (become depressed) when they are clicked.
    Currently, I have found some way to handle click events on them, but the display is not updated to show that they are clicked.
    How can this be done??
    fyi, the click code adds a mouse listener to the table, which determines which cell is clicked based on location and forwards the event to appropriate handler. it goes something like this:
    private void forwardEventToHandlers(MouseEvent e) {
             TableColumnModel columnModel = _table.getColumnModel();
             _column = columnModel.getColumnIndexAtX(e.getX());
             _row    = e.getY() / _table.getRowHeight();
             Object value;
             JButton button = new JButton();
             MouseEvent buttonEvent;
             if(_row >= _table.getRowCount() || _row < 0 ||
                _column >= _table.getColumnCount() || _column < 0)
               return;
             value = _table.getValueAt(_row, _column);
                              // forward an event to handler...
             }

    I have a couple of attempts at this that you may be able to use or at least give you some ideas:
    a) Original attempt
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableButton extends JFrame
        public TableButton()
            String[] columnNames = {"Date", "String", "Integer", "Decimal", "Boolean"};
            Object[][] data =
                {new Date(), "A", new Integer(1), new Double(5.1), new JButton("Delete")},
                {new Date(), "B", new Integer(2), new Double(6.2), new JButton("Delete")},
                {new Date(), "C", new Integer(3), new Double(7.3), new JButton("Delete")},
                {new Date(), "D", new Integer(4), new Double(8.4), new JButton("Delete")}
            DefaultTableModel model = new DefaultTableModel(data, columnNames);
            final JTable table = 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();
                //  Don't edit the button column
                public boolean isCellEditable(int row, int column)
                    return column != 4;
            table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
            //  Create button renderer
            TableCellRenderer buttonRenderer = new ButtonRenderer();
            table.setDefaultRenderer(JButton.class, buttonRenderer);
            //  Add table mouse listener
            table.addMouseListener( new ButtonListener(table, 4) );
        public static void main(String[] args)
    //        try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }
    //        catch(Exception e) {}
            TableButton frame = new TableButton();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
        class ButtonRenderer extends JButton implements TableCellRenderer
            public Component getTableCellRendererComponent(
                JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
                JButton button = (JButton)value;
                if (button == null)
                    setText( "" );
                    getModel().setPressed( false );
                    getModel().setArmed( false );
                else
                    setText( button.getText() );
                    getModel().setPressed( button.getModel().isPressed() );
                    getModel().setArmed( button.getModel().isArmed() );
                return this;
         *  1) Creation of class will determine the column to process mouse events on
         *  a) Mouse pressed will determine the row to process and paint pressed button
         *  b) Mouse clicked will do the actual processing
         *  c) Mouse released will paint the normal button
        class ButtonListener extends MouseAdapter
            private JTable table;
            //  Column from the data model to process mouse events on
            private int column;
            //  The table row when the mouse was pressed
            private int row;
            //  The table column when the mouse was pressed
            private int tableColumn;
            //  Repaint the button on mouse released event
            private boolean paintOnRelease;
            ButtonListener(JTable table, int column)
                this.table = table;
                this.column = column;
             *  Repaint button to show pressed state
            public void mousePressed(MouseEvent e)
                //  Make sure the MouseEvent was on the button column
                if ( !buttonColumn(e) ) return;
                //  Repaint the button for the current row/column
                row = table.rowAtPoint( e.getPoint() );
                tableColumn = table.columnAtPoint( e.getPoint() );
                paintButton( true );
                paintOnRelease = true ;
             *  Do table processing on this event
            public void mouseClicked(MouseEvent e)
                //  Make sure the MouseEvent was on the button column
                if ( !buttonColumn(e) ) return;
                //  Only process a single click
                if (e.getClickCount() > 1) return;
                //  Delete current row from the table
                DefaultTableModel model = (DefaultTableModel)table.getModel();
                model.removeRow( this.row );
                //  Row has been deleted, nothing to repaint
                paintOnRelease = false;
             *  Repaint button to show normal state
            public void mouseReleased(MouseEvent e)
                if (paintOnRelease)
                    paintButton( false );
                paintOnRelease = false;
            private boolean buttonColumn(MouseEvent e)
                //  In case columns have been reordered, we must map the
                //  table column to the data model column
                int tableColumn = table.columnAtPoint( e.getPoint() );
                int modelColumn = table.convertColumnIndexToModel(tableColumn);
                return modelColumn == column;
            private void paintButton(boolean pressed)
                //  Make sure we have a JButton before repainting
                Object o = table.getValueAt(row, tableColumn);
                if (o instanceof JButton)
                    JButton button = (JButton)o;
                    button.getModel().setPressed( pressed );
                    button.getModel().setArmed( pressed );
                    table.setValueAt(button, row, tableColumn);
    }b) Latest attempt:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableButton3 extends JFrame
        public TableButton3()
            String[] columnNames = {"Date", "String", "Integer", "Decimal", ""};
            Object[][] data =
                {new Date(), "A", new Integer(1), new Double(5.1), "Delete0"},
                {new Date(), "B", new Integer(2), new Double(6.2), "Delete1"},
                {new Date(), "C", new Integer(3), new Double(7.3), "Delete2"},
                {new Date(), "D", new Integer(4), new Double(8.4), "Delete3"}
            DefaultTableModel model = new DefaultTableModel(data, columnNames);
            JTable table = 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();
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
            //  Create button column
            ButtonColumn buttonColumn = new ButtonColumn(table, 4);
        public static void main(String[] args)
            TableButton3 frame = new TableButton3();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
        class ButtonColumn extends AbstractCellEditor
            implements TableCellRenderer, TableCellEditor, ActionListener
            JTable table;
            JButton renderButton;
            JButton editButton;
            String text;
            public ButtonColumn(JTable table, int column)
                super();
                this.table = table;
                renderButton = new JButton();
                editButton = new JButton();
                editButton.setFocusPainted( false );
                editButton.addActionListener( this );
                TableColumnModel columnModel = table.getColumnModel();
                columnModel.getColumn(column).setCellRenderer( this );
                columnModel.getColumn(column).setCellEditor( this );
            public Component getTableCellRendererComponent(
                JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
                if (hasFocus)
                    renderButton.setForeground(table.getForeground());
                    renderButton.setBackground(UIManager.getColor("Button.background"));
                else if (isSelected)
                    renderButton.setForeground(table.getSelectionForeground());
                     renderButton.setBackground(table.getSelectionBackground());
                else
                    renderButton.setForeground(table.getForeground());
                    renderButton.setBackground(UIManager.getColor("Button.background"));
                renderButton.setText( (value == null) ? "" : value.toString() );
                return renderButton;
            public Component getTableCellEditorComponent(
                JTable table, Object value, boolean isSelected, int row, int column)
                text = (value == null) ? "" : value.toString();
                editButton.setText( text );
                return editButton;
            public Object getCellEditorValue()
                return text;
            public void actionPerformed(ActionEvent e)
                fireEditingStopped();
                System.out.println( e.getActionCommand() + " : " + table.getSelectedRow());
    }

  • Please Help! - Refreshing a JTable ( JDBC)

    Hi
    Currently I am populating a JTable with data from an Access database.
    I have not yet created my own Table Model.
    My table is displayed in a frame with a button to the side which when clicked creates a dialog box which enables the user to input data. Clicking the OK button on this dialog box then updates the database and the dialog box is removed.
    The problem is that the table is not updated with this newly input data.
    I have tried using
    ((AbstractTableModel)table1.getModel()).fireTableDataChanged();
    which doesn't work.
    If I create my own Table Model and then call on the fireTableDataChanged method,will this update the table? I want the table to update as soon as the dialog box is closed.
    I really would appreciate any help here. The JTable tutorial doesn't really help.
    Thanks
    LGS

    Would you agree that it would be better to requery the database incase another user has subsequently posted new recordsConcurrency shouldn't be a problem, but if it buys you peace of mind, then do it.
    Also -are you saying that I really should have my own Table Model? You should, this will give you more control over the operations of the table.
    If you want to see how I implement DB access in my table, check out the imports from and exports to external databases at the link shown below:
    http://www.aokabc.com
    ;o)
    V.V.

  • Couldn't show sql data in jtable, please help

    Dear All,
    I'm trying to display the data from database in a jtable by following the jtable demo example in Java Tutorials Sample Code; but, I couldn't output the data to the jtable. The following code is what I've done so far. Can anybody please point out a direction for showing the data in jtable? Thanks a lot in advance.
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    public class Patient {
    static String szJdbcURL = "jdbc:oracle:thin:@129.78.110.188:1521:MyDB";                
    static String szUser = "...";                
    static String szPasswd = "...";                
    static String szModelName = "...";
    static Oracle oracle = new Oracle(szJdbcURL, szUser, szPasswd);
    public void findMedication() throws SQLException{
      Statement stmt1 = null;
      try {
             stmt1=oracle.getConnection().createStatement();             
              String res1=null;
              String res2=null;                
         String sqlQuery="Select * From PatientTable ";
            ResultSet rs= stmt1.executeQuery(sqlQuery);
       if (!rs.isBeforeFirst())
             {System.out.println("OOPS! data not found.");
              System.out.println(); }
       else {
        while (rs.next()) {
       ArrayList<Medication> medList = new ArrayList<Medication>();
       res1=rs.getString("patientName");
       res2=rs.getString("medication");
       Medication med=new Medication (res1, res2);
       medList.add(med);
       System.out.println();
       finally {stmt1.close();}
    import java.util.ArrayList;
    public class Medication {
        String ptName;
        String ptMedication;
    public Medication(String ptName, String ptMedication){
      this.ptName=ptName;
      this.ptMedication=ptMedication;
    public String getPtName() {
      return ptName;
    public void setPtName(String ptName) {
      this.ptName = ptName;
    public String getPtMedication() {
      return ptMedication;
    public void setPtMedication(String ptMedication) {
      this.ptMedication = ptMedication;
    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;
    import java.util.ArrayList;
    public class TableDemo extends JPanel {
      private boolean DEBUG = false;
    public TableDemo () {
      super(new GridLayout(1,0));
      ArrayList<Medication> medList = new ArrayList<Medication>();
      //how to add the data to the ArrayList here?
            JTable table = new JTable(new MyTableModel(medList));
            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 {
         private String[] columnNames = new String []{"Patient Name", "Medication"};
         ArrayList<Medication> medList = null;
        public MyTableModel (ArrayList<Medication> medList){
         this.medList=medList;
           public int getColumnCount() {  
         return columnNames.length;
       public int getRowCount() {
        return medList.size();
       public String getColumnName(int columnIndex) {
            return columnNames[columnIndex];
    public Object getValueAt(int rowIndex, int columnIndex) {
      Medication object = medList.get(rowIndex);
            switch (columnIndex) {
            case 0:
                 return object.getPtName();
            case 1:
                 return object.getPtMedication();   
            default:
                 return "unknown";
    @SuppressWarnings("unchecked")
    public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
         private static void createAndShowGUI() {
             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) {
             javax.swing.SwingUtilities.invokeLater(new Runnable() {
                 public void run() {
                     createAndShowGUI();

    This line will create an ArrayList which will be used to store the output data of the sql query with the type is Medication class
    NO! Read what TPD ask again carefully -
    Please explain (as explicit as you can) what these two lines do.
    Did you notice that TWO in there?
    Did you notice that your reply said 'This line' when it should have said 'These TWO lines .'?
    You are creating a new ArrayList EVERY TIME thru the loop; you are NOT creating ONE ArrayList and adding things to it.
    The problem is how to show the ArrayList in the jtable defined in another class.
    And the answer is: use one of the THOUSANDS of examples on the internet.
    See the trail 'How to Use Tables' in The Java Tutorials
    http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
    Read the trail - try the example. You learn by doing and using code that already works.

  • Sorting ArrayList multiple times on Multiple Criteria

    I have an arraylist that is sorted with Collection.sort() calling the ComparTo() included below. CompareTo sorts the file on totalLaps, totalSeconds, and etc.. The question is how do I change the sort criteria later in my process so that the arraylist is sorted on sequence number (the first field and a long number)? The only way I can currently think of doing it is to copy the array and create a separate class file like RaceDetail2 that implements a different CompareTo. To me that seems ridiculous!
    I've self tought myself Java using the online tutorials and a few books so sometimes I find I have some basic gaps in knowledge about the language. What am I missing? Seems like it should be simple.
    private ArrayList detailsArrayList = new ArrayList( );
    // Sort arraylist using compareTo method in RaceDetail file
    Collections.sort(detailsArrayList);
    public class RaceDetail implements Comparable, Cloneable {
         public RaceDetail( long seqNum, String boatNumText, int lapNum, String penalty, String question, long seconds, int totalLaps, long totalSecs, long lastSeqNum, long avg, long interval )
    public int compareTo( Object o )
         RaceDetail rd = (RaceDetail) o;
         int lastCmp = (totalLaps < rd.totalLaps ? -1: (totalLaps == rd.totalLaps ? 0: 1));
         int lastCmpA = boatNumText.compareTo(rd.boatNumText);
         int lastCmpB = (lapNum < rd.lapNum ? -1: (lapNum == rd.lapNum ? 0 : 1 ));
         int lastCmpC = (totalSecs < rd.totalSecs ? -1 : (totalSecs == rd.totalSecs ? 0 : 1 ));
         int lastCmpD = (seqNum < rd.seqNum ? -1 : (seqNum == rd.seqNum ? 0 : 1 ));
         int lastCmpE = (seconds < rd.seconds ? -1 : (seconds == rd.seconds ? 0 : 1 ));
         int lastCmpF = (lastSeqNum < rd.lastSeqNum ? -1 : (lastSeqNum == rd.lastSeqNum ? 0 : 1 ));
         // TotalLaps - Descending, TotalSeconds - ascending, lastSeqNum - ascending
         // Boat - Ascending, Second - ascending, seqNum - ascending
         return (lastCmp !=0 ? -lastCmp :
              (lastCmpC !=0 ? lastCmpC :
                   (lastCmpF !=0 ? lastCmpF :
                        (lastCmpA !=0 ? lastCmpA :
                             (lastCmpE !=0 ? lastCmpE :
                                  lastCmpD)))));
    }

    Thanks talden, adding the comparator below in my main program flow worked and now the arraylist sorts correctly. A couple of additional questions. I tried to place this in my RaceDetail class file and received a compile error so placed it in the main program flow and it worked fine. For organization, I would like to place all my sort routines together. Is there some trick to calling this method if I place it in my RaceDetail? Am I even allowed to do that?
    dhall - just to give you a laugh, this arraylist populates a JTable, uses a TableModel, and the TableSorter from the tutorial. Sorting works great in the JTable. Problem is I have to sort the arraylist a couple of times to calculate some of the fields such as lap times and total laps. I went through the TableSorter 5 or 6 times and never could figure out how to adapt it for what I wanted to do. So here I am using an example in my program and can't interpret it.
    Collections.sort( detailsArrayListLeft, SORT_BY_SEQUENCE );
    static final Comparator SORT_BY_SEQUENCE = new Comparator() {
    public int compare ( Object o1, Object o2 )
         RaceDetail rd1 = (RaceDetail) o1;
         RaceDetail rd2 = (RaceDetail) o2;
         return (rd1.seqNum() < rd2.seqNum() ? -1 : (rd1.seqNum() == rd2.seqNum() ? 0 : 1 ));

  • RMI with JTable

    hi
    I have created a rmi application where the client searches for some data on the server, and then displays the found data in a JTable on the client side.
    I am having some trouble populating the Jtable on the client side. First of all, I tried to get the data as a String[] array; and then tried to add a new row to my table as 'defaultTable.addRow(string)'. But this did not turn out to be good.
    Then I tried to get the data as a vector. Part of my code is below:
    String name=file.getAttributeValue("name");
                        String directory =file.getAttributeValue("directory");
                        String size = file.getAttributeValue("size");
                        String[] data= {name,directory,size};
                        System.out.println( "name is " name " directory is "+ directory +" size is "+ size);
                        //Vector vector=new Vector();
                        vector.toArray(data);
    return vector;
    And on the client side I add this vector to my table as follows:
    try
                             vector=server.searchForFiles(searchEntry);
                             Object[] string=vector.toArray();
                             defaultTable.addRow(string);
    With this approach, I can add rows to my table, but the actual data is not displayed.
    So does anyone know how I need to get the data from the server and add it in a table on the client side.
    (I am using DefaultTableModel)
    regards
    Qasim

    Not really.
    at client side I have code such as below:
    private DefaultTableModel defaultTable= new DefaultTableModel();
         private JTable table ;
    tablePanel.setLayout(new FlowLayout());
              defaultTable.addColumn("Name");
              defaultTable.addColumn("Directory");
              defaultTable.addColumn("Size");
    table= new JTable(defaultTable);
    and I thought that I could use defaultTable.addRow(...) to add another row to this defaultTable;but abviously I can't since I need to add more than just one row to this table.

  • ViewObjects, Jtables and custom cellrenderers

    Hi,
    I'm wondering if someone knows a solution to this type of a problem.
    I have a ViewObject bound to a Jtable. Simple enough. Now when I add a new record to this ViewObject manually (not throught the nav bar); the record is already populated, my jtable updates correctly to show that the row has been entered. Now here is the problem:
    I have a custom cellRenderer that is displaying a JComboBox. Now based on the data that is stored on our Database and what row is currently being rendered, the checkbox is either disabled or enabled. Trouble is, as soon as there become more records in the JTable than there is room on the screen assigned to the JTable, my JScrollPane's vertical scrollbar kicks in, which is good and no problems, but every checkbox for all the rows that are displayed when scrolling are disabled.
    Now the reason for this is simple. Code below.
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    boolean state = false;
    if (String.valueOf(value).equals(onValue))
    state = true;
    else if ((String.valueOf(value).equals(offValue)) || (value == null))
    state = false;
    else
    throw new IllegalStateException("warning: unrecognized value: " + value);
    JCheckBox box = new JCheckBox();
    box = new JCheckBox();
    box.setSelected(state);
    box.setHorizontalAlignment(SwingConstants.CENTER);
    if (isSelected)
    box.setBackground(SystemColor.textHighlight);
    else
    box.setBackground(SystemColor.window);
    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.setEnabled(table.isCellEditable(row, column));
    panel.add(box, BorderLayout.CENTER);
    if (hasFocus)
    panel.setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
    else
    panel.setBorder(emptyBorder);
    if (isSelected)
    panel.setBackground(SystemColor.textHighlight);
    else
    panel.setBackground(SystemColor.window);
    if(isDisabled(row, column))
    box.setEnabled(false);
    else
    box.setEnabled(true);
    return panel;
    private boolean isDisabled(int row, int column)
    Row aRow = tableView.getRowAtRangeIndex(row);
    System.out.println("ROW: " + row);
    if(aRow != null)
    if(aRow.getAttribute("DboType").toString().toUpperCase().compareTo("TABLE") == 0)
    if(column < 5)
    return false;
    else
    return true;
    }else if(aRow.getAttribute("DboType").toString().toUpperCase().compareTo("PACKAGE") == 0)
    if(column == 5)
    return false;
    else
    return true;
    }else
    return true;
    }else if(aRow == null)
    System.out.println("SHOULD NOT BE NULL");
    return true;
    else
    return true;
    The line:
    Row aRow = tableView.getRowAtRangeIndex(row);
    returns null!!! how can this be? Considering tableView is my ViewObject and tableView is the viewObject that is bound to the JTable? It's almost as if the JTable is increasing in size before the ViewObject has it'self added the new row to it's self and the transaction cache?
    Now before you say, "Why don't you just add DBO_TYPE to the JTable?", well because we don't want it displayed to the user. If we did this then I'm somewhat sure it would work, but we should not have to add data to the JTable just for this considering the ViewObject already stores this information, but is just not displaying it onto the screen.
    Any help?

    Haven't checked at all (it's Sunday night for God's sake!) but are we sure it's nothing to do with the fact that getRowAtRangeIndex is relative to the currently displayed rows and the row passed in from the table is absolute?
    Mike.

  • JTable  with headers extending JDialog

    I am creating a class file extending JDialog. I have populated the JTable on the form and want to include headers on the table. The dialog form opens and the table is visible and populated but with no headers. Has anyone had success with headers on JTables when creating a JDialog object?
    I have other tables created with headers so I wondered if the problem was with JDialog?

    inorder to make headers visible you need to add scroll pane to table,
    either by:
    JScrollPane scrollPane = JTable.createScrollPaneForTable(table);
    or:
    scrollPane = new JScrollPane(table);
    unless there's no scroller, you can't see headers.

  • How to use ArrayList to represent muti-dimension array?

    For example, how to use ArralyList to represent array likes this:
    a[0][0] = xxx
    a[1][1] = xxx
    a[2][2] = xxx
    .....Thanks

    For example, how to use ArralyList to represent array likes this:
    > a[0][0] = xxx
    a[1][1] = xxx
    a[2][2] = xxx
    .....Use an ArrayList populated with ArrayLists?
    kind regards,
    Jos

  • Using the swing worker to populate the data in to jtablle

    Hello, i am developing my 1st application in java swings , i have developed it but when i run a module which fetchces the data from the mysql and display it in jtable my swing gui got blank for some initial time, i was thinking for some progress bar type thing but when i came acroos google i found that i can use swing worker to load my GUI on time and in the back ground i can do the task of fetching the data from the data base and populating the Jtable, but i had done a lot of try but not succeded to implement the swing worker . Please help me to implement the swing worker :( . i am using the abstractTableModal to populating the jtable it is working fine but swing worker is not there .
    Scenerio is like this i have base frame on which i got 1 or more btton one of those button is Clients when i click on it a Jdialog box appears with the jtable . Pleae tell me how to implement the swing worker class between this. Pleaseeeeeeeeeeeeeeeeeeeeee :( I am help less now .

    Fahim i want to display some photograph in to a swing application after fetching these photo graph from the database table , i dont know what swing component will be better for it and i m designing this in netbeans , so please assist me with that , how to go now and please note that it is dynamic so component should be like that :(. i m trying to create a photo album where i upload the multiple photograph first then i would like to show them each photograph will a text box when some one write some text in that text box and press enter i would like to save that text with that photo graph , I AM DONE WITH THE PHOTO UPLOADING TASK BUT DONT KNOW HOW TO DO THE REST LIKE DISPLAYING THE PHOTOGRAPH WITH THAT TEXT BOX .
    Edited by: kamal.java on Apr 27, 2012 8:59 AM

  • How to populate a jsf table with an array?

    I have a JSF project where I'm using a table and I would like to populate that table with some custom information without using a database. I'm trying to write my own data provider. I was wondering if anyone knows how to populate a jsf table using an array. Any help would be appreciated. Thanks.

    Hey thanks for replying. I'm not quite sure what you mean, but I am using a woodstock table in Netbeans. I would love to skip writing the data provider since I've never done that before, but I'm not sure how I would go about populating the table with a regular List or Model. I have populated a JTable with my own model, but never a woodstock table. They don't seem to work the same way. Thanks for the help. I've spent hours trying to figure this out.

  • Why Do We Need Constructor With Arguments?

    I understand that constructor is used to create instances.
    We can have constructors with 0 argument or with one/multiple arguments. Why do we need a contructor with arguments? What is the purpose of doing it?
    Thank you for your help.

    There are three general ways to provide constructors, like you said:
    1) Default constructor (no arguments)
    2) One or more constructors with arguments
    3) One or more constructors with arguments as well as a default constructor
    From a design standpoint, the idea is to give as much information needed for constructing an object up front. Look at the standard Java API for some examples (and because I couldn't find a standard class with just a default constructor, one made up):
    public class Foo {
      private long createTime;
      public Foo() {
        createTime = System.currentTimeMillis();
      public String toString() {
        return "This object was created at " + createTime;
    }This code has no reason to take any arguments. It does all construction on its own and already has all the information it needs. On the other hand, look at BufferedReader. There's no possible way this object can ever be constructed without an argument. What's it buffering? It doesn't make sense to ever instantiate new BufferedReader(). It'd be useless. So BufferedReader has no default (no-arg) constructor.
    Sometimes (very often in Java) you want to do both. Let something be instantiated with no arguments, but also provide the option of creating something with more specific details. A good example is ArrayList, which has three constructors:
    public ArrayList() --> Construct an empty ArrayList with the default initial capacity;
    public ArrayList(Collection c) --> Construct an ArrayList populated with the contents of another collection;
    public ArrayList(int capacity) --> Construct an empty ArrayList with a specific initial capacity.
    Sometimes it makes sense just to use the default. Sometimes you want more control over the behavior. Those are the times to use multiple constructors.
    Hope this helps!

Maybe you are looking for

  • Macbook Pro seems to "shutdown" for a few seconds.

    When i say shutdown, I don't mean, literally close all applications and then power down. What happens is the computer will pause any music, videos playing, or any other activity make the screen go black, and make the backlit keyboard no longer backli

  • Using 64-bit java on Solaris 10 x86

    Hello, I just got a new X2100 server and installed Solaris 10 on it. Everything's running fine and I installed the most recent x86 64-bit jdk 1.5 update on it. However, I can't find any detailed info on how to set the amd64 java binaries and env as t

  • Off topic question please.

    I am flying next week from New York JFK airport to London. I bought a new AirPort Extreme that I wish to bring with me. Where should I put the router ? : In my personal Troll that comes with me to the plain , OR Leave it inside my big souitcase that

  • Conversation view in OWA 2010 - Super-duper slow expansion

    Hello, I know it has been asked countless time to disable conversation in OWA and that it can't be done. I think it's a great feature but the problem we face is that conversation expansion take a very (very) long time, sometimes looping forever when

  • Starting the new editor results in short dump

    Hi gurus, When I switch to the new ABAP editor in Nteweaver 7.0 I get a short dump when opening an ABAP source. The message says: message_type_x Does anybody know what the problem is? We are working with SAPGUI 6.40 patch 16. Working in the old front