Connect a list of objects to a JTable

12,555

Solution 1

In Model-View-Controller Architecture the model is always responsible for the provision of data. If you use a model for your JTable the model provides the data.

In order to create a model make a separate class that extends AbstractTableModel and has a constructor that creates all the SI objects you need and stores them to an ArrayList.

 public class FinalTableModel extends AbstractTableModel {

    private List<SI> li = new ArrayList();
    private String[] columnNames = { "Recipe", "Order", "Instruction",
                "Est.time", "Timer", "Timer Label", "Has Subinstructions"};

    public FinalTableModel(List<SI> list){
         this.li = list;
    }

    @Override
    public String getColumnName(int columnIndex){
         return columnNames[columnIndex];
    }

    @Override     
    public int getRowCount() {
        return li.size();
    }

    @Override        
    public int getColumnCount() {
        return 7; 
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        SI si = list.get(rowIndex);
        switch (columnIndex) {
            case 0: 
                return si.getRecipe();
            case 1:
                return si.getMakingOrder();
            case 2:
                return si.getInstruction();
            case 3:
                return si.getEstimatedTimeInMinutesSeconds();
            case 4:
                return si.getTimerInMinutesSeconds();
            case 5:
                return si.getTimerEndingText();
            case 6:
                return si.isContainsOtherInstructions(); 
           }
           return null;
   }

   @Override
   public Class<?> getColumnClass(int columnIndex){
          switch (columnIndex){
             case 0:
               return String.class;
             case 1:
               return Integer.class;
             case 2:
               return String.class;
             case 3:
               return Double.class;
             case 4:
               return Double.class;
             case 5:
               return String.class;
             case 6:
               return Boolean.class;
             }
             return null;
      }
 }

Then make your JFrame and and create your JTable like this:

    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();

    jTable1.setModel(new FinalTableModel(finalList));
    jScrollPane1.setViewportView(jTable1);

The idea is that JTable will autamatically request the data from the model, through call to getValueAt(row, col).

Netbeans makes it very easy to assign the model to your JTable. The model is a property of the JTable. Click the '...' button and choose "Custom code". Underneath create a model instance.

enter image description here

Solution 2

It's easier to use DefaultTableModel, but then you'll need to not use an ArrayList, but rather the data model held by the DefaultTableModel, though you could use your ArrayList to load the model.

You could construct the DefaultTableModel with an array of your column titles and 0 rows, and then add rows in a for loop, using your ArrayList above to create a Vector<Object> or an Object[], and then feed that into the model with its addRow method. Note that you could not add SI objects as a row, but instead would have to extract the data from each SI object and put it into the Object array or Object Vector.

If you instead go the AbstractTableModel route, you would use your own data structure for the nucleus of the model, and so here, your ArrayList would work just fine, but you'd be responsible for a lot more of the heavier lifting. It's not impossible to do, but would require a little more work. You may wish to look through Rob Camick's webtip blog as it has some decent model examples. You can find it here: Java Tips Weblog. In particular, please check out it's Row Table Model entry.

Share:
12,555

Related videos on Youtube

Ioannis Soultatos
Author by

Ioannis Soultatos

Updated on June 04, 2022

Comments

  • Ioannis Soultatos
    Ioannis Soultatos almost 2 years

    I have a list of objects of type SI (SingleInstruction) in Java. Here is the SI class with its constructor.

        public class SI {
            private String recipe;
            private Integer makingOrder;
            private String instruction;
            private double estimatedTimeInMinutesSeconds;
            private Double timerInMinutesSeconds;
            private String timerEndingText;
            private boolean containsOtherInstructions = false;
            private List<SI> embeddedInstructionsList;
    
            public SI (String s1, Integer i1, String s2, double d1, Double d2, String s3){
                recipe = s1;
                makingOrder = i1;
                instruction = s2;
                estimatedTimeInMinutesSeconds = d1;
                timerInMinutesSeconds = d2;
                timerEndingText = s3;
            }
    setters and getters methods ommited....
    

    I need to have a table in my GUI that displays the data of this list. When I begin the program I create a

    public List<SI> finalList = new ArrayList();
    

    which is empty so I need an empty table to be displayed. The table should have columns of

    (String Recipe, Integer Order, String Instruction, double Est.time, Double Timer, String TimerText, boolean containOtherInstructions)

    Afterwards the finalList is filled with data and I need these data to be displayed in the table. In order to give you an example, I created a button that creates some SI and adds them to the finalList.

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        SI si1 = new SI("Greek Salad", 1, "cut veggies", 4, null, null);
        SI si2 = new SI("Greek Salad", 2, "put spices", 1, null, null);
        SI si3 = new SI("Greek Salad", 3, "feta and finish", 1, null, null);
        SI si4 = new SI("Break", null, "Your free 10 minutes", 10, null, null);
        SI si5 = new SI("Meat", 1, "preheat oven", 0.5, 10.0, "oven is ready");
        SI si6 = new SI("Meat", 2, "spices on meat", 2, null, null);
        SI si7 = new SI("Meat", 3, "cook meat", 1, 10.0, "meat is ready");
        SI si8 = new SI("Meat", 4, "serve", 1, null, null);
        SI si9 = new SI("Break", null, "Your free 10 minutes", 10, null, null);
        SI si10 = new SI("Jelly", 1, "Boil water", 0.5, 4.0, "water is ready");
        SI si11 = new SI("Jelly", 2, "add mix and stir", 4, null, null);
        SI si12 = new SI("Jelly", 3, "share in bowls, wait 3 hours", 2, null, null);
        finalList.add(si1);
        finalList.add(si2);
        finalList.add(si3);
        finalList.add(si4);
        finalList.add(si5);
        finalList.add(si6);
        finalList.add(si7);
        finalList.add(si8);
        finalList.add(si9);
        finalList.add(si10);
        finalList.add(si11);
        finalList.add(si12);
    }
    

    Now I need that when I press the button, the table is updated and displays the data. I've tried a lot to find out how to do it but it is too hard. I'm not sure if I should extend AbstractTableModel or just use the defaultTableModel.

    To help you give me suggestions, the data of this table is final and user can't modify any cell. what should be allowed to the user to do though is to move rows up or down to change the order in the finalList.

    PS: I am using netbeans, if you have any quick suggestions on the GUI builder.

  • Ioannis Soultatos
    Ioannis Soultatos over 12 years
    I see that i shouldn't use the DefaultTableModel as i want to dynamically move the data in my finalList. row table model is like the abstract model with the difference that it gives you more methods to play with rows and doesn't care much about columns, right? if that's the case i prefer it from the abstract. i cant figure out the code to connect the list with the table though.
  • Hovercraft Full Of Eels
    Hovercraft Full Of Eels over 12 years
    If you use the DefaultTableModel, you can dynamically move the data as well, so that's not a restriction. The main restriction towards use of DefaultTableModel is that you wouldn't be dealing with SI objects directly but rather with the data that the SI objects hold. As to "figuring the code", that's something you're going to have to work on. If you get stuck with a specific problem though, show us your attempt and we'll probably be able to help you.
  • Ioannis Soultatos
    Ioannis Soultatos over 12 years
    i have created my model class extends abstractTableModel, i know my column names so i passed them in private String[] columnNames =.. i got the methods initially required like getColumnCount(), getRowCount(), getColumnName(int col), getValueAt but i dont know how to pass my list in ' private Object[][] data = { }'. in other posts the input data manually ' private Object[][] data = { { "hgflig", "Campione", "Snowboarding", new Integer(5), new Boolean(false) }' but i don't know how to pass my list of SI there. Any suggestions how to pass the object in there?
  • camickr
    camickr over 12 years
    +1, The `RowTableModel' is just a starting point for displaying rows of Objects. You would want to use the Bean Table Model for a complete implementation. It also has an example that shows you how to manually extend the RowTableModel to implement the two required methods.
  • Ioannis Soultatos
    Ioannis Soultatos over 12 years
    i m checking it now... i m doing well, i managed to get the data on a table using the defaultmodel but i need another model to do the job.. i will let you know soon. thanx for helping
  • Ioannis Soultatos
    Ioannis Soultatos over 12 years
    i ve tried to work with the bean model but i just can't do it. i m lost trying to decode it. i think i m too amateur for this... i managed though to do my model and pass my list in it similar to the post below. i m almost there... cheers though