This discussion is archived
3 Replies Latest reply: Dec 25, 2012 5:49 AM by TPD-Opitz-Consulting-com RSS

Create a JTable based on an ArrayList containing instances of a class.

978884 Newbie
Currently Being Moderated
I have a class, IncomeBudgetItem, instances of which are contained in an ArrayList. I would like to create a JTable, based on this ArrayList. One variable is a string, while others are type double. Not all variables are to appear in the JTable.

The internal logic of my program is already working. And my GUI is largely constructed. I'm just not sure how to make them talk to each other. The actually creation of the JTable is my biggest problem right now.
  • 1. Re: Create a JTable based on an ArrayList containing instances of a class.
    980759 Newbie
    Currently Being Moderated
    you can check demo
    http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TableDemoProject/src/components/TableDemo.java
    in this demo you can covert Object[][] data to ArrayList

    The below method used to specify type of the column
     public Class getColumnClass(int c) {             return getValueAt(0, c).getClass();         } 
  • 2. Re: Create a JTable based on an ArrayList containing instances of a class.
    980759 Newbie
    Currently Being Moderated
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.util.ArrayList;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    
    public class TableDemo extends JPanel {
         private boolean DEBUG = false;
    
         public TableDemo() {
              super(new GridLayout(1, 0));
    
              ArrayList<MyObject> list = new ArrayList<MyObject>();
              list.add(new MyObject("Kathy", "Smith", "Snowboarding", new Integer(5),
                        new Boolean(false)));
              list.add(new MyObject("John", "Doe", "Rowing", new Integer(3),
                        new Boolean(true)));
              list.add(new MyObject("Sue", "Black", "Knitting", new Integer(2),
                        new Boolean(false)));
              list.add(new MyObject("Jane", "White", "Speed reading",
                        new Integer(20), new Boolean(true)));
              JTable table = new JTable(new MyTableModel(list));
              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 MyObject {
              String firstName;
              String lastName;
              String sport;
              int years;
              boolean isVeg;
    
              MyObject(String firstName, String lastName, String sport, int years,
                        boolean isVeg) {
                   this.firstName = firstName;
                   this.lastName = lastName;
                   this.sport = sport;
                   this.years = years;
                   this.isVeg = isVeg;
              }
         }
    
         class MyTableModel extends AbstractTableModel {
              private String[] columnNames = { "First Name", "Last Name", "Sport",
                        "# of Years", "Vegetarian" };
              ArrayList<MyObject> list = null;
    
              MyTableModel(ArrayList<MyObject> list) {
                   this.list = list;
              }
    
              public int getColumnCount() {
                   return columnNames.length;
              }
    
              public int getRowCount() {
                   return list.size();
              }
    
              public String getColumnName(int col) {
                   return columnNames[col];
              }
    
              public Object getValueAt(int row, int col) {
    
                   MyObject object = list.get(row);
    
                   switch (col) {
                   case 0:
                        return object.firstName;
                   case 1:
                        return object.lastName;
                   case 2:
                        return object.sport;
                   case 3:
                        return object.years;
                   case 4:
                        return object.isVeg;
                   default:
                        return "unknown";
                   }
              }
    
              public Class getColumnClass(int c) {
                   return getValueAt(0, c).getClass();
              }
         }
    
         /**
          * 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();
                   }
              });
         }
    }
  • 3. Re: Create a JTable based on an ArrayList containing instances of a class.
    TPD-Opitz-Consulting-com Expert
    Currently Being Moderated
    The table model should also implement getColumnClass(int) so the JTable will automatically care for checkboxes and number alignments...
    public Class<?> getColumnClass(int columnIndex){
      switch (columnIndex)
        case 0: return String.class;
        case 1: return String.class;
        case 2: return String.class;
        case 3: return Date.class;
        case 4: return Boolean.class;
        default: throw new IndexOutOfBoundsException(columnIndex+" > 4");
    }
    -----
    And now, having 2 switch statements you could think of removing them in favor of an enumeration:
     private static enum TableColumn{
       FIRST_NAME {
           Object getValue(MyObject myObject ) { return myObject.firstName);}
           Class<?> getColumnClass() { return String.class;}
      }, LAST_NAME  {
           Object getValue(MyObject myObject ) { return myObject.lastName);}
           Class<?> getColumnClass() { return String.class;}
      }, SPORTS {
           Object getValue(MyObject myObject ) { return myObject.sports);}
           Class<?> getColumnClass() { return String.class;}
      }, YEAR  {
           Object getValue(MyObject myObject ) { return myObject.year);}
           Class<?> getColumnClass() { return Date.class;}
      }, IS_VEGETARIAN {
          private Object getValue(MyObject myObject ) { return myObject.isVeg);}
          private Class<?> getColumnClass() { return Boolean.class;}
      };
       abstract  Object getValue();
       abstract Class<?> getColumnClass();
    }
    
    public int  getColumnCount() {
      return TableColumn.values().size();
    }
    
    public Object getValueAt(int row, int col) {
        MyObject object = list.get(row);
        TableColumn currentColumn = TableColumn.values()[col];
        return currentColumn.getValue(object);
    }
    public Class<?> getColumnClass(int columnIndex){
      TableColumn currentColumn = TableColumn.values()[col];
      return currentColumn.getColumnClass();
    }
    bye
    TPD

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points