JTable e modelli

Stato
Discussione chiusa ad ulteriori risposte.

Varro

Utente Silver
29 Aprile 2008
47
6
0
68
Salve a tutti, sto bazzicando il sito della Sun da stamattina ma non riesco a trovare una soluzione che sia calzante con il mio problema.
Nel programma che sto sviluppando, ho una JTable i cui elementi vengono ricavati da un FrontController.
Dopo richieste di inserimento e/o cancellazione, avrei bisogno di refreshare i dati dal FrontController.
Ho creato quindi una inner class che estende AbstractTableModel.
Quando lo dò in pasto alla tabella va tutto benissimo.
Quando però uso il metodo setModel(new MyTableModel()) per ricaricare il tutto, non succede assolutamente nulla. La cosa mi lascia un pò interdetto perchè pensavo seguisse lo stesso concetto delle JList per le quali non vi era alcun problema con il setModel.
Spero abbiate qualche idea a riguardo perchè sono ore che ci sbatto la testa ma non riesco a trovare una soluzione pulita (Non ditemi di reistanziare la tabella per piacere :p)
Cordialità
 
Sto avendo un pò di emergenze a casa e più tardi posto un pò di codice, anche se credo di aver trovato stranamente la soluzione.

EDIT: Sto terminando di risolvere un problema e ne approfitto per lanciare un'altra sfida :p impiegare HashMap all'interno di TableModel, in modo che la chiave non sia visibile, ma all'atto della selezione di una riga, vi sia la restituzione di tale chiave

EDIT2: Nonostante nonna con femore fratturato all'ospedale e cane malaticcio son riuscito a risolvere tutto, non appena ho un fiato posto il codice così può aiutare un pò di gente :)
Al prossimo post
 
Classe astratta generica per un pannello contenente un JTable

Codice:
package ui.panelli;

import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import java.util.List;

import javax.swing.JButton;
import javax.swing.BorderFactory;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import ui.utilities.GridBagLayoutUtility;
import ui.utilities.elementi.ElementoTabella;

import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;


public abstract class PannelloTabellaGenerico extends JPanel  {

	private static final long serialVersionUID = 1L;
	private JPanel pannelloTabella = null;
	private JPanel pannelloBottoni = null;
	protected JScrollPane pannelloScrollabile = null;
	protected JTable tabella = null;

	/**
	 * This is the default constructor
	 */
	public PannelloTabellaGenerico() {
		super();
		initialize();
	}

	/**
	 * This method initializes pannelloScrollabile
	 *
	 * @return javax.swing.JScrollPane
	 */
	protected JScrollPane getPannelloScrollabile() {
		if (pannelloScrollabile == null) {
			pannelloScrollabile = new JScrollPane();
			pannelloScrollabile.setViewportView(getTabella());
		}
		return pannelloScrollabile;
	}

	/**
	 * This method initializes tabellas
	 *
	 * @return javax.swing.JTable
	 */
	protected JTable getTabella() {
		if (tabella == null) {
			tabella = new JTable();

			tabella.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			tabella.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
				public void propertyChange(java.beans.PropertyChangeEvent e) {
					if ((e.getPropertyName().equals("model"))) {
     				    getPannelloScrollabile().setViewportView(tabella);
     				   if (tabella.getSelectedRow() == -1)
     					   setEditableButtons(false);
     				   else
     					   setEditableButtons(true);
					}
				}
			});
			tabella.addMouseListener(new java.awt.event.MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					if (tabella.getSelectedRow() == -1)
  					   setEditableButtons(false);
  				   else
  					   setEditableButtons(true);
				}
			});
		}
		return tabella;
	}

	/**
	 * This method initializes panelloDestra
	 *
	 * @return javax.swing.JPanel
	 */
	protected JPanel getPannelloBottoni() {
		if (pannelloBottoni == null){
			pannelloBottoni = new JPanel();
			pannelloBottoni.setLayout(new GridBagLayout());
		}
		return pannelloBottoni;
	}

	protected abstract void setEditableButtons(boolean b);

	protected abstract void refreshModelloTabella();

	protected boolean isListaVuota(){
		if (getTabella().getModel().getRowCount() == 0)
			return true;
		else
			return false;
	}

	protected void addButton(JButton bottone){
		GridBagLayoutUtility formUtility = new GridBagLayoutUtility();
		formUtility.addLastField(bottone, getPannelloBottoni());
	}

	/**
	 * This method initializes this
	 *
	 * @return void
	 */
	private void initialize() {
		this.setLayout(new BorderLayout());
		this.add(getPannelloTabella(), BorderLayout.CENTER);
		this.add(getPannelloBottoni(), BorderLayout.EAST);
	}

	/**
	 * This method initializes pannelloTabella
	 *
	 * @return javax.swing.JPanel
	 */
	private JPanel getPannelloTabella() {
		if (pannelloTabella == null) {
			pannelloTabella = new JPanel();
			pannelloTabella.setLayout(new BorderLayout());
			pannelloTabella.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 5));
			pannelloTabella.add(getPannelloScrollabile(), BorderLayout.CENTER);
		}
		return pannelloTabella;
	}

	protected abstract class ModelloTabella extends AbstractTableModel {

		protected String[] columnNames = null;

        protected List<ElementoTabella> data = null;

        public ModelloTabella(String[] columnNames, List<String> elenco) {
        	this.columnNames = columnNames;
        	initializeData(elenco);
        }

        protected abstract List<ElementoTabella> initializeData(List<String> elenco);

        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.size();
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data.get(row).getData()[col];
        }

        public String getRowKey(int row) {
            return data.get(row).getKey().toString();
        }
	}
}

Classe che estende la classe astratta di cui prima
Codice:
package ui.panelli;

import java.awt.Component;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import ui.dialogs.DialogDettagliInsegnamento;
import ui.dialogs.DialogInserisciInsegnamento;
import ui.utilities.DialogsUtility;
import ui.utilities.elementi.ElementoTabella;
import filters.FiltroInsegnamento;
import frontController.FrontController;

public class PannelloTabellaInsegnamenti extends PannelloTabellaGenerico{
	private static final long serialVersionUID = 1L;
	private JButton bottoneInserisci = null;
	private JButton bottoneDettagli = null;
	private JButton bottoneCancella = null;

	final String[] nomiColonne = {"Denominazione", 
								  "Corso di laurea"};

	/**
	 * This is the default constructor
	 */
	public PannelloTabellaInsegnamenti() {
		super();
		initialize();
	}

	private void initialize() {
		addButton(getBottoneInserisci());
		addButton(getBottoneDettagli());
		addButton(getBottoneCancella());
		setEditableButtons(false);

		refreshModelloTabella();
	}

	protected void refreshModelloTabella(){
		getTabella().setModel(new ModelloTabellaInsegnamenti(nomiColonne, FiltroInsegnamento.filtraElencoInsegnamentiTabellaToUI(FrontController.getInstance().elencoInsegnamenti())));
	}

	protected void setEditableButtons(boolean attivo) {
		getBottoneDettagli().setEnabled(attivo);
		getBottoneCancella().setEnabled(attivo);
	}

	/**
	 * This method initializes bottoneInserisci
	 *
	 * @return javax.swing.JButton
	 */
	private JButton getBottoneInserisci() {
		if (bottoneInserisci == null) {
			bottoneInserisci = new JButton();
			bottoneInserisci.setText("Inserisci");
			bottoneInserisci.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					new DialogInserisciInsegnamento((JFrame) SwingUtilities.getRoot((Component) e.getSource())).setVisible(true);
					refreshModelloTabella();
				}
			});
		}
		return bottoneInserisci;
	}

	/**
	 * This method initializes bottoneDettagli
	 *
	 * @return javax.swing.JButton
	 */
	private JButton getBottoneDettagli() {
		if (bottoneDettagli == null) {
			bottoneDettagli = new JButton();
			bottoneDettagli.setText("Dettagli");
			bottoneDettagli.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					new DialogDettagliInsegnamento((JFrame) SwingUtilities.getRoot((Component) e.getSource()), Integer.parseInt(((ModelloTabellaInsegnamenti) getTabella().getModel()).getRowKey(getTabella().getSelectedRow()))).setVisible(true);
					refreshModelloTabella();
				}
			});
		}
		return bottoneDettagli;
	}

	/**
	 * This method initializes bottoneCancella
	 *
	 * @return javax.swing.JButton
	 */
	private JButton getBottoneCancella() {
		if (bottoneCancella == null) {
			bottoneCancella = new JButton();
			bottoneCancella.setText("Cancella");
			bottoneCancella.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					if (!FrontController.getInstance().cancellaInsegnamento(Integer.parseInt(((ModelloTabellaInsegnamenti) getTabella().getModel()).getRowKey(getTabella().getSelectedRow()))))
						DialogsUtility.showErrorMessage((JFrame) SwingUtilities.getRoot((Component) e.getSource()));
					else
						refreshModelloTabella();
				}
			});
		}
		return bottoneCancella;
	}

	 class ModelloTabellaInsegnamenti extends ModelloTabella {

		 /**
		 *
		 */
		private static final long serialVersionUID = 1L;

		public ModelloTabellaInsegnamenti(String[] columnNames, List<String> elenco) {
			super(columnNames, elenco);
		}

		@Override
		protected List<ElementoTabella> initializeData(List<String> elenco) {
			data = new ArrayList<ElementoTabella>();
			for (String i: elenco)
				data.add(new ElementoTabella(i, FiltroInsegnamento.filtraInsegnamentoTabellaToUI(FrontController.getInstance().leggiDatiInsegnamento(Integer.parseInt(i)))));
			return data;
		}
	 }
}
 
Stato
Discussione chiusa ad ulteriori risposte.