Issue with Listener on a JTable (executes code too many times) Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Issue with Listener on a JTable (executes code too many times) without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am currently trying to use a listener on my Jtable but as it turns out, the Event gets called once for every item on the table, which makes it very slow. Here’s the code I’m using:

tabProductos.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
        if (e.getClickCount() == 2) {
            int idProducto = (int) tabProductos.getValueAt(tabProductos.getSelectedRow(), 0);
            System.out.println(idProducto);
            asignarProdcuto(idProducto);
        }
    }
});

The same Thing happens with this other Listener:

tabProductos.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
    @Override
    public void valueChanged(ListSelectionEvent e) {
        if (!tabProductos.getSelectionModel().isSelectionEmpty()) {
            int idProducto = (int) tabProductos.getValueAt(tabProductos.getSelectedRow(), 0);
            System.out.println(idProducto);
            asignarProdcuto(idProducto);
        }
    }
});

The variable “idProducto” is printed exactly as many times as there are items on the table. The number is correct.

I’ve tried with “e.getValueIsAdjusting()” for the Second one but it has been of no use.

here’s the complete Method:

   public void cargarProductos(ArrayList<Producto> productos) {

        DefaultTableModel tm = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        String[] cabecera = {"ID", "Nombre", "Detalle", "Precio Unit.", "idP", "Proveedor"};
        tm.setColumnIdentifiers(cabecera);
        for (Producto p : productos) {
            Object[] row = {p.getId(), p.getNombre(), p.getTamaƱo(), p.getPrecioUnitario(), p.getProveedor().getId(), p.getProveedor().getNombre()};
            tm.addRow(row);
            tabProductos.setModel(tm);
            tabProductos.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    if (e.getClickCount() == 2) {
                  int idProducto = (int) tabProductos.getValueAt(tabProductos.getSelectedRow(), 0);
                        System.out.println(idProducto);
                    }
                }
            });
            tabProductos.getColumn("ID").setMaxWidth(36);
            tabProductos.setAutoCreateRowSorter(true);
            tabProductos.getTableHeader().setReorderingAllowed(false);
        }
    }

Thanks

Answer

You’re adding your MouseListener multiple times to the JTable inside of the for loop — bad news since multiple listeners will fire when the table is clicked on. The solution is don’t do this. Instead create your JTable, set its model and then after doing this, add the MouseListener to the JTable, but only once.

Perhaps something like (code not tested):

public void cargarProductos(ArrayList<Producto> productos) {

    DefaultTableModel tm = new DefaultTableModel() {
        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };
    String[] cabecera = {"ID", "Nombre", "Detalle", "Precio Unit.", "idP", "Proveedor"};
    tm.setColumnIdentifiers(cabecera);
    for (Producto p : productos) {
        Object[] row = { p.getId(), p.getNombre(), p.getTamaƱo(), p.getPrecioUnitario(), 
                p.getProveedor().getId(), p.getProveedor().getNombre()};
        tm.addRow(row);
    }

    // do all of this **after** the for loop, not inside it
    tabProductos.setModel(tm);
    tabProductos.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                int idProducto = (int) tabProductos.getValueAt(tabProductos.getSelectedRow(), 0);
                System.out.println(idProducto);
            }
        }
    });
    tabProductos.getColumn("ID").setMaxWidth(36);
    tabProductos.setAutoCreateRowSorter(true);
    tabProductos.getTableHeader().setReorderingAllowed(false);
}
We are here to answer your question about Issue with Listener on a JTable (executes code too many times) - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji