Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 15
  1. #1
    Utente di HTML.it L'avatar di 1sirena
    Registrato dal
    Mar 2008
    Messaggi
    163

    cancellazione riga selezionata jtable

    Ciao a tutti!!


    Sono riuscita a visualizzare i dati presenti nel mio database in una jTable e ora vorrei che l'utente avesse la possibilità di aggiornare il database dalla jTable.
    Non riesco a capire come si cancella una riga selezionata... Sul Web non sono riuscita a trovare nulla... Sapete dirmi come si fa??

  2. #2
    Utente di HTML.it
    Registrato dal
    May 2008
    Messaggi
    142
    dovrebbero bastarti queste righe.
    Rimuovi il listener , estrai il modello e poi procedi con la rimozione.

    codice:
                jTable.getModel().removeTableModelListener(ChangeTable);
                DefaultTableModel model =(DefaultTableModel)jTable.getModel();
                model.removeRow(jTable.getSelectedRow());
    nel codice mostrato rimuove la riga selezionata!

  3. #3
    Utente di HTML.it L'avatar di 1sirena
    Registrato dal
    Mar 2008
    Messaggi
    163
    scusa non ho capito bene cosa devo fare...

    il codice che mi hai dato lo devo aggiungere all'evento del click del bottone cancella??

  4. #4
    Utente di HTML.it
    Registrato dal
    May 2008
    Messaggi
    142
    devi modificare il nome della tabella ( da jTable al nome della tua tabella ) così come il nome del listener (nel mio caso ChangeTable nel tuo non so)

    poi devi mettere quel codice nel
    codice:
    jButtonActionPerformed(java.awt.event.ActionEvent evt) {  }
    del tuo bottone "cancella".

  5. #5
    Utente di HTML.it L'avatar di 1sirena
    Registrato dal
    Mar 2008
    Messaggi
    163
    non mi riconosce il metodo removeRow()...
    Ti posto il codice! secondo te cosa sbaglio?
    La classe ModTab estende la AbstractTableModel e calcola il numero di colonne e righe per la visualizzazione della JTable.


    codice:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.FocusTraversalPolicy;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Arrays;
    
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.border.BevelBorder;
    import javax.swing.border.SoftBevelBorder;
    
    import com.jgoodies.forms.layout.CellConstraints;
    import com.jgoodies.forms.layout.FormLayout;
    
    /**
    *
    * @author Roby
    */
    public class Table2 extends JFrame implements ActionListener{
    /**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    
    private JButton tabella;
    private JPanel scatola; 
    
    private JTable t;
    public Connection conn;
    private JButton cancella;
    
    /** Costruttore Data*/
    public Table2() {
    super("prova database");
    setSize(500,250);
    setLocation(200,200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    
    tabella = new JButton("DATI IN TABELLA");
    scatola = new JPanel();
    
    
    
    
    tabella.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
    try {
    leggitabella(e);
    } catch (SQLException ex) {
    ex.printStackTrace();
    } 
    }
    });
    
     
    
    scatola.setLayout(null);
    add(scatola); 
    
    
    scatola.add(tabella);
    tabella.setBounds(300,170,150,30);
    
    
    }
    
    
    
    public static void main(String[] args){ 
    
    Table2 visualizza = new Table2();
    visualizza.setVisible(true);
    } 
    
    public void actionPerformed(ActionEvent e) {
    }
    
    // il metodo leggi dati leggi idati dall’archivio e li visualizza in una nuova finestra
    
    public void leggidati(ActionEvent e) throws SQLException{
    // Costruzione nuova finestra
    JDialog finestra = new JDialog();
    JTextArea lavagna = new JTextArea();
    Font f = new Font(" ", Font.BOLD,15); 
    lavagna.setFont(f);
    finestra.setTitle("finestra di dialogo col database");
    finestra.setSize(400,400);
    finestra.setLocation(300,200);
    finestra.setVisible(true); 
    finestra.setLayout(new BorderLayout());
    finestra.add(BorderLayout.CENTER,new JScrollPane(lavagna)); 
    finestra.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    
    }
    
    
     // fine leggidati
    
    // parte relative alla visualizzazione dei dati in una tabella
    
    @SuppressWarnings("serial")
    
    
    
    // il metodo leggitabella fa vedre il dislay dei dati in una tabella in una nuova finestra
    
    public void leggitabella(ActionEvent e) throws SQLException{
    
    // costruzione nuova finestra
    
    JDialog finestra2 = new JDialog();
    JPanel PannelloBottoni = new JPanel();
    cancella = new JButton("Cancella");
    
    	
    JButton modifica = new JButton("Modifica");
    @SuppressWarnings("unused")
    //JTextArea lavagna2 = new JTextArea();
    Font f2 = new Font(null, Font.BOLD,15); 
    ModTab miomodello = new ModTab("Utente");
    t = new JTable(miomodello);
    finestra2.add("North", t);
    finestra2.add("South", PannelloBottoni);
    FormLayout PAnnelloBottoniLayout = new FormLayout(
    		"27dlu, 117dlu, 66dlu, 117dlu", 
    		" 17dlu, 37dlu, max(p;5dlu)");		
    PannelloBottoni.setLayout(PAnnelloBottoniLayout);
    PannelloBottoni.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
    PannelloBottoni.setBackground(new Color(0, 51, 255));
    PannelloBottoni.setPreferredSize(new java.awt.Dimension(542, 171));
    PannelloBottoni.add(cancella, new CellConstraints("2, 3, 1, 1, default, default"));
    PannelloBottoni.add(modifica, new CellConstraints("4, 3, 1, 1, default, default"));
    cancella.addActionListener(new ActionListener() {
    	
    	
    
    	
    
    	@Override
    	public void actionPerformed(ActionEvent arg0) {
    		// TODO Auto-generated method stub
    		t.getModel().removeTableModelListener(ChangeTable);
            ModTab model =(ModTab)t.getModel();
            model.removeRow(t.getSelectedRow());
    
    	}
    
    	
    	
    } 
    
    );
    
    finestra2.add(t);
    finestra2.setFont(f2);
    finestra2.setTitle("visualizzazione dati in tabella");
    finestra2.setSize(1280, 775);
    //finestra2.setLocation(0,0);
    finestra2.setVisible(true); 
    finestra2.setLayout(new BorderLayout());
    finestra2.add(BorderLayout.NORTH,new JScrollPane(t)); 
    finestra2.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); 
    
    
    
    } // fine leggitabella 
    
    }

  6. #6
    Utente di HTML.it L'avatar di 1sirena
    Registrato dal
    Mar 2008
    Messaggi
    163
    Ho provato in questo modo:

    codice:
    ...................
    cancella.addActionListener(new ActionListener() {
    	
    	
    
    	
    
    	@Override
    	public void actionPerformed(ActionEvent evt) {
    		// TODO Auto-generated method stub
    		t.setRowSelectionAllowed(true);
    		t.setColumnSelectionAllowed(false);
    		t.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    		String Key = (String) t.getModel().getValueAt(t.getSelectedRow(),1);
    		SQLManager sql = new SQLManager("com.mysql.jdbc.Driver","jdbc:mysql://localhost:3306/schedule","root","root");
    		SQLManager.cancella(Key);
    		sql.close();
    		
    
    	}
    } );
    e nel file che permette la connessione al database e l'esecuzione delle query:

    codice:
    ...................
    public static PreparedStatement cancella (String Key) {
    			try{ 
    				String d = "DELETE FROM Utente WHERE id_utente = ?";
    					PreparedStatement pstmt = conn.prepareStatement(d);
    					pstmt.setString(1, Key);
    					pstmt.executeUpdate();
    						
    			}catch(Exception ex){ 
    				ex.printStackTrace(); 
                 	}
    			return pstmt; 
    			
        	 
        		}
    Mandandolo in esecuzione mi da le seguenti eccezioni:
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
    at org.schedule.prova.ModTab.getValueAt(ModTab.java:3 0)
    at org.schedule.prova.Table2$2.actionPerformed(Table2 .java:156)
    at javax.swing.AbstractButton.fireActionPerformed(Unk nown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed (Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed (Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(U nknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unkno wn Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(U nknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
    at org.schedule.prova.ModTab.getValueAt(ModTab.java:3 0)
    at org.schedule.prova.Table2$2.actionPerformed(Table2 .java:156)
    at javax.swing.AbstractButton.fireActionPerformed(Unk nown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed (Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed (Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(U nknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unkno wn Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(U nknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

  7. #7
    Utente di HTML.it L'avatar di 1sirena
    Registrato dal
    Mar 2008
    Messaggi
    163
    Ora non mi da nessun tipo d'errore e di eccezione...
    Ma se non seleziono nessuna riga mi visualizza il messaggio d'errore "Non esiste l'oggetto selezionato", mentre se seleziono una riga e clicco sul pulsante cancella entra nel catch visualizzandomi il messaggio d'errore "Non esiste l'oggetto selezionato"

    Ho provato in questo modo:

    actionListner del pulsante "cancella"
    codice:
    cancella.addActionListener(new ActionListener() {
    	
    	public void actionPerformed(ActionEvent evt) {
    		{
    				
    		try{
    					if(t.getSelectedRow()==-1){//se non hai selezionato niente
    					JOptionPane.showMessageDialog(null,"Non hai selezionato niente", "Attenzione",JOptionPane.ERROR_MESSAGE);
    					}else{
    						t.setRowSelectionAllowed(true);
    						t.setColumnSelectionAllowed(false);
    						t.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    						String key = (String) t.getModel().getValueAt(t.getSelectedRow(),4);
    						SQLManager sql = new SQLManager("com.mysql.jdbc.Driver","jdbc:mysql://localhost:3306/schedule","root","root");
    						sql.cancella(key);
    
    						sql.close();	
    						
    				}
    				
    			}
    				catch(Exception ex){
    									
    					
    					JOptionPane.showMessageDialog(null,"Non esiste l'oggetto selezionato", "Attenzione",JOptionPane.ERROR_MESSAGE);
    	
    				
    				}
    				
    			//} 
    	}}
    	} );
    Metodo cancella sito nel file che permette la connessione:
    codice:
    public void cancella (String docente) throws SQLException {
    			
    				String d = "DELETE FROM Utente WHERE id_utente = ?";
    					PreparedStatement pstmt = conn.prepareStatement(d);
    					pstmt.setString(4, docente);
    					pstmt.executeUpdate();
    			}
    Perchè nessuno mi risponde??

  8. #8
    la scritta "non esiste l'oggetto selezionato" compare quando c'è un'eccezione. Nel catch non la stampi a video ma c'è. Fatti stampare lo stacktrace dell'eccezione.
    Al mio segnale... scatenate l'inferno!

  9. #9
    Utente di HTML.it L'avatar di 1sirena
    Registrato dal
    Mar 2008
    Messaggi
    163
    hO MODIFICATO IN QUESTO MODO:

    codice:
    cancella.addActionListener(new ActionListener() {
    	
    	public void actionPerformed(ActionEvent evt) {
    		{
    				try{
    					if(t.getSelectedRow()==-1){//se non hai selezionato niente
    					JOptionPane.showMessageDialog(null,"Non hai selezionato nessuna riga", "Attenzione",JOptionPane.ERROR_MESSAGE);
    					}else{
    						t.setRowSelectionAllowed(true);
    						t.setColumnSelectionAllowed(false);
    						t.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    						int key = (Integer) t.getModel().getValueAt(t.getSelectedRow(),4);
    						SQLManager sql = new SQLManager("com.mysql.jdbc.Driver","jdbc:mysql://localhost:3306/schedule","root","root");
    						sql.cancella(key);
    
    						
    				sql.close();	
    						
    				}
    				
    			}
    			catch(Exception ex){
    									
    				ex.printStackTrace();
    					//JOptionPane.showMessageDialog(null,"Non esiste l'oggetto selezionato", "Attenzione",JOptionPane.ERROR_MESSAGE);
    	
    				
    				}
    				
    			
    	}}
    	} );
    e mi da le seguenti eccezioni:

    java.lang.ArrayIndexOutOfBoundsException: -1
    at org.schedule.prova.ModTab.getValueAt(ModTab.java:3 0)
    at org.schedule.prova.Table2$2.actionPerformed(Table2 .java:158)
    at javax.swing.AbstractButton.fireActionPerformed(Unk nown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed (Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed (Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(U nknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unkno wn Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(U nknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

  10. #10
    Utente di HTML.it L'avatar di 1sirena
    Registrato dal
    Mar 2008
    Messaggi
    163
    Se non è il metodo giusto per cancellare potete darmi qualche altro consiglio??


Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.