Connect a JTable object with a Collection object

0

I have a public Collection<Suppliers> getAllSuppliers() method which obviously returns the data from the suppliers table.

In the client part swing I try to show in a JFrame an object JTable containing the records of the table.

Runnable runner = new Runnable()
    {
        @Override
        public void run()
        {
            Facade facade = new Facade();
            Collection<Suppliers> suppliers = facade.getAllSuppliers();

            JFrame frame = new JFrame("JTable Data");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 600);

            Container content = frame.getContentPane();
            content.setLayout(new BorderLayout());


            frame.setVisible(true);
        }
    };
    EventQueue.invokeLater(runner);

I'm starting on the theme of applications swing the model MVC , I'm trying to pass the object suppliers which contains a collection of suppliers to DefaultTableModel but without success. Do I have to change the interface Collection ?

Thanks for your time

    
asked by David Leandro Heinze Müller 29.11.2016 в 12:01
source

1 answer

1

For what you ask you have to use a TableModel to load the data and pass it to your JTable . I recommend using a DefaultTableModel with your constructor DefaultTableModel(Object[][] data, Object[] columnNames) .

I leave you the most basic example that I have done so that you can see the connection with the information that you have given us. 1.- We will load the data and the names of the columns to create the model with them:

Object[] columnas = new Object[]{"Descripción Supplier"};
Object[][] datos = new Object[suppliers.size()][columnas.length];

Iterator iterator = suppliers.iterator();

for(int i = 0; i < suppliers.size(); i++){
    datos[i][0] = iterator.next();
}

2.- With the data loaded, we instantiate the TableModel :

DefaultTableModel model = new DefaultTableModel(datos, columnas);

3.- Finally you have to present them. As fast as a pop-up message to see it:

JScrollPane panel = new JScrollPane(new JTable(model));
JOptionPane.showMessageDialog(null, panel, "EJEMPLO SUPPLIERS", JOptionPane.PLAIN_MESSAGE);

If you had put more information you could have adjusted more to what you need. Right now your Suppliers objects are loaded integers in a single column. % default DefaultTableModel renders the cell as String , so it will call the toString() method to fill the cell.

If you load the data argument with the different attributes, these will appear according to the load order under each column that you declared in the columna object in the same order. As there may be very different data we use Object which is generic, but you can create reders for each cell to show what you want.

Some programming languages seem to make it easier to "connect" data as you say, but the power of Java doing it in this way has no limits.

    
answered by 29.11.2016 / 13:06
source