Issue edit a jtable with a pictures

28 Views Asked by At

I'm struggling to edit a Jtabel with a picture on it. So basically, I can edit the table ONLY if I edit the picture on it. I can't edit anything if I am not editing the column on the picture on it: trying to debug but the listener isn't doing the query on the server.

here's the code

public class VisualizzaprodottiPanel extends JPanel {
  // Attribut
  private JTable jtable;
  private ListaProdottiTableModel tableModel;
  private Set<Integer> righeModificate = new HashSet<>(); // Set per tenere traccia delle righe modificate

  // Costruttore
  public VisualizzaprodottiPanel() {
    setLayout(new BorderLayout());

    // Creazione del modello della tabella e inizializzazione dei dati
    IArticoloDAO articoloDAO = ArticoloDAO.getInstance();
    List<Prodotto> prodotti = articoloDAO.findAll();
    tableModel = new ListaProdottiTableModel(prodotti, articoloDAO);

    // Creazione della tabella con il modello
    JTable tabellaProdotti = new JTable(tableModel);
    tabellaProdotti.setRowHeight(100); // Altezza della riga
    tabellaProdotti.setShowGrid(false); // Nasconde le linee di griglia
    tabellaProdotti.setIntercellSpacing(new Dimension(0, 0)); // Nessuno spazio tra le celle

    JButton modifica = new JButton("Modifica");

    Map<Integer, String> imagePathMap = new HashMap<>();


    modifica.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        DbOperationExecutor executor = new DbOperationExecutor(); //conn database

        for (int row : righeModificate) {
          Prodotto p = new Prodotto();
          p.setId(prodotti.get(row).getId()); //gestire dopo la roba degli id
          p.setNome(tabellaProdotti.getValueAt(row,0).toString());
          p.setTipoProdotto(IArticolo.TIPO_PRODOTTO.valueOf(tabellaProdotti.getValueAt(row,1).toString()));
          p.setDisponibilita(Integer.valueOf(tabellaProdotti.getValueAt(row,2).toString()));
          p.setPrezzo(Float.valueOf(tabellaProdotti.getValueAt(row,3).toString()));
          p.setFoto(imagePathMap.get(row));
          p.setDescrizione(tabellaProdotti.getValueAt(row,5).toString());
          articoloDAO.updateProdotto(p);
        }
        // Pulisci il set delle righe modificate dopo l'aggiornamento nel database
        righeModificate.clear();
      }
    });

    tabellaProdotti.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        int column = tabellaProdotti.columnAtPoint(evt.getPoint());
        if (column == 4) { // Controlla se il click è sulla colonna delle immagini
          int row = tabellaProdotti.rowAtPoint(evt.getPoint());
          JFileChooser fileChooser = new JFileChooser();
          fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
          int result = fileChooser.showOpenDialog(VisualizzaprodottiPanel.this);
          if (result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            String imagePath = selectedFile.getAbsolutePath();
            imagePath = imagePath.replace("\\", "\\\\");
            // Aggiorna il percorso dell'immagine nel modello della tabella
            tableModel.setValueAt(imagePath, row, column);
            // Aggiungi la riga modificate al set
            righeModificate.add(row);
            imagePathMap.put(row, imagePath);
          }
        }
      }
    });

    JScrollPane scrollPane = new JScrollPane(tabellaProdotti);
    add(scrollPane, BorderLayout.CENTER);
    add(modifica, BorderLayout.SOUTH);

  }
}

The Table Model that im working with it( i dont think the problem is there)

public class ListaProdottiTableModel extends AbstractTableModel {

  private List<Prodotto> prodotti = new ArrayList<>();
  private IArticoloDAO articoloDAO;

  public ListaProdottiTableModel(List<Prodotto> prodotti, IArticoloDAO articoloDAO) {
    this.prodotti = prodotti;
    this.articoloDAO = articoloDAO;
  }

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

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

  @Override
  public Object getValueAt(int rowIndex, int columnIndex) {
    Prodotto prodotto = prodotti.get(rowIndex);
    switch (columnIndex) {
      case 0: return prodotto.getNome();
      case 1: return prodotto.getTipoProdotto();
      case 2: return prodotto.getDisponibilita();
      case 3: return prodotto.getPrezzo();
      case 4:
         String imagePath = prodotto.getFoto();
        if (imagePath != null && !imagePath.isEmpty()) {
          ImageIcon imageIcon = new ImageIcon(imagePath);
          Image image = imageIcon.getImage();
          Image scaledImage = image.getScaledInstance(100, 100, Image.SCALE_SMOOTH);
          return new ImageIcon(scaledImage);
        }else {
          return null;
        }
      case 5: return prodotto.getDescrizione();
      default:return null;
    }
    }


  @Override
  public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    Prodotto prodotto = prodotti.get(rowIndex);
    switch (columnIndex) {
      case 0: prodotto.setNome((String) aValue); break;
      case 1:  // Converte la stringa in enum
        try {
          IArticolo.TIPO_PRODOTTO tipoProdotto = IArticolo.TIPO_PRODOTTO.valueOf((String) aValue);
          prodotto.setTipoProdotto(tipoProdotto);
        } catch (IllegalArgumentException e) {
          // Gestisce il caso in cui la stringa non corrisponda a nessun valore dell'enum
          // Potresti mostrare un messaggio di errore o gestire il caso in un altro modo appropriato
          System.out.println("Valore non valido per il tipo di prodotto.");
        }
        break;

      case 2:  try {
        int disponibilita = Integer.parseInt((String) aValue);
        prodotto.setDisponibilita(disponibilita);
      } catch (NumberFormatException e) {
        System.out.println("Errore durante la conversione della disponibilità in intero.");
      }
        break;


      case 3: prodotto.setPrezzo((float) aValue); break;
      case 4: prodotto.setFoto((String) aValue); break;
      case 5: prodotto.setDescrizione((String) aValue); break;
    }
    // Aggiorna il prodotto nel database
    //articoloDAO.updateProdotto(prodotto);
    // Aggiorna la tabella
    fireTableRowsUpdated(rowIndex, rowIndex);
  }

  @Override
  public Class<?> getColumnClass(int columnIndex) {
    if (columnIndex == 4) {
      return ImageIcon.class; // Immagine
    } else {
      return super.getColumnClass(columnIndex);
    }
  }

  @Override
  public boolean isCellEditable(int rowIndex, int columnIndex) {
    return true;
  }


}

Maybe the problem is on the mouseLister but i cant solve the problem.

0

There are 0 best solutions below