0

I am trying to populate a jtable from the data I get using mongoDB,this is the code i have:

JButton btnLista = new JButton("Listado");
        btnLista.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                
                MongoClient conexion = new MongoClient("localhost", 27017);
                DB base = conexion.getDB("dbunidad5");
                DBCollection tabla = base.getCollection("vehiculos");
                DBCursor cursor = tabla.find();
                String[] columns = {"matricula","marca","modelo","precio"};
                DefaultTableModel model = new DefaultTableModel(columns,0);
                         
                 while (cursor.hasNext()) {
                DBObject obj = cursor.next();
                 String matricula = (String)obj.get("matricula");
                 String marca = (String)obj.get("marca");
                 String modelo = (String)obj.get("modelo");
                 String precio = (String)obj.get("precio").toString();
                 model.addRow(new Object[] {matricula,marca,modelo,precio});     
                 }
                 tblVehiculos = new JTable();
                 tblVehiculos.setVisible(true);
                 cursor.close();
                 conexion.close();
            }
        });

It doesnt`t give me any error but the table with the data doesnt show up. Can anyone help me and tell me what i´m doing wrong?

Thanks

prasad_
  • 12,755
  • 2
  • 24
  • 36
Dario
  • 1
  • You still need to add the model to the JTable. – prasad_ May 13 '21 at 11:03
  • Even after i added the columns and rows,it still doesnt work – Dario May 13 '21 at 11:58
  • Where is the JTable displayed? It needs to be in a container like JFrame or a JDialog. See this post about Why is My JTable not Showing Up: https://stackoverflow.com/questions/10684275/why-is-my-jtable-not-showing-up – prasad_ May 13 '21 at 12:14
  • Thanks! I was able to display the JTable but doesnt seem to get the data from the MongoDB. Is my code wrong? – Dario May 13 '21 at 12:28
  • 1
    1) Don't use a MouseListener on the button. The JButton was designed to be used with an `ActionListner` to handle a mouse click. 2) Swing components are visible by default, there is no need to invoke setVisible(true) on the table. 3) We can't debug your code. Add debug statements to your logic to see what values are returned from the database 4) Generally you would create the table and add it to the frame when the frame is created. Then when you click your button you would just create the TableModel and Invoke the setModel(...) method of the JTable to update the data. – camickr May 13 '21 at 14:48

0 Answers0