0

I have re-structured my GUI according to the MVC pattern, but I am not sure how to populate a JTable in my view. So far, my code is:

VIEW:

public class GUIview extends JFrame {
...
    // set Table Inputs info
public void setTableInfo(List<Object[]> listTable) {
    for (int i = 0; i < listTable.size(); i++) {
        Object[] tempArray = listTable.get(i);
        ((DefaultTableModel) getTableModel()).insertRow(i, tempArray);
    }
}

CONTROLLER.

public class GUIcontroller {
...
       m_view.setTableInfo(m_model.getList());

MODEL

public class GUImodel {
...
    public List<Object[]> getList() {
        return resultsList;
    }

I would like to code as close as possible to MVC. Is this the most suitable approach? I mean, the View should not contain code just for rendering the view. I am thinking about move the "for" loop to the controller, and then just call a view-function for the insertRow. Is is better?

capovawi
  • 377
  • 8
  • 21

2 Answers2

1

In the GUI you just have to set the model to the JTable and the TableModel should do all the data related issues like adding rows, removing rows, setting values, updating cell values.

You can go through this example.

Community
  • 1
  • 1
Amarnath
  • 8,736
  • 10
  • 54
  • 81
  • Thanks Che. I have reviewed this [example](http://stackoverflow.com/a/15658573/2373397) , but where should I place the classes "TableData" and "AllTableModel" ?? Do I have to create a proper file for them? Or maybe turn them into inner classes of my "GUIview" class? – capovawi May 24 '13 at 13:32
  • No for Inner class. Create a separate class for `TableModel`. Populate data in the model either getting it from the file (say a separate `fileIO` class) or write a method in the model that returns dummy data in the model. – Amarnath May 24 '13 at 16:50
0

I think you should add elements to model and if everything is setup ok, table should be filled on screen.

KernelPanic
  • 2,328
  • 7
  • 47
  • 90
  • Could you explain a little bit in more detail? I have thought about using jGoodies Binding framework, is that what you say? Thx Marko Frelih – capovawi May 24 '13 at 09:09
  • Well, according to [JTable docs](http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html), first you should subclass TableModel, which containts data itself. Then you apply model to JTable via setModel and then you subclass cell renderer. – KernelPanic May 24 '13 at 09:42
  • mmm, that sounds interesting and quite logical. Let´s investigate... Thanks again Marko Frelih – capovawi May 24 '13 at 09:57