Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 11
  1. #1

    Inserire JButton in una cella di una JTable

    il tutorial oracle (http://docs.oracle.com/javase/tutori...le.html#editor) dice che i JButton non possono essere nativamentei impostati all'interno di una jtable. e va bene...

    Ora sto provando a ridefinire il CellEditor ma mi sono perso da qualche parte...

    allora ho creato il mio render personalizzato a pulsante, come da esempio:
    codice:
    package graphicComponent;
    
    import java.awt.Component;
    import java.util.Map;
    import java.util.WeakHashMap;
    import javax.swing.AbstractCellEditor;
    import javax.swing.JButton;
    import javax.swing.JTable;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    
    public class TableButtonRender extends AbstractCellEditor
            implements TableCellRenderer, TableCellEditor {
    
        private Map<String, JButton> renderButtons = new WeakHashMap<String, JButton>();
    
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int row, int column) {
            JButton button = (JButton) value;
            JButton renderButton = renderButtons.get(button.getText());
    
            if (renderButton == null) {
                renderButton = new JButton(button.getText());
                renderButtons.put(button.getText(), renderButton);
            }
    
            return renderButton;
        }
    
        @Override
        public Object getCellEditorValue() {
            return null;
        }
    
        @Override
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
            return (JButton) value;
        }
    }
    e pensavo che bastasse richiamarlo in questo modo:

    codice:
        private void visualizzaTabella() {
            HashMap<String, Protocollo> listaProtocolli = this.archivioProtocollo.getListaProtocolli();
            Set<String> chiavi = this.archivioProtocollo.getListaProtocolli().keySet();
            int rigaTabella = 0;
            TableModel model = this.tabellaProtocollo.getModel();
    
            TableColumn column = this.tabellaProtocollo.getColumnModel().getColumn(8);
            TableButtonRender render=new TableButtonRender();
            column.setCellRenderer(render);
    
    
            ((DefaultTableModel) model).setNumRows(listaProtocolli.size() + 1);
            for (String key : chiavi) {
                final Protocollo protocollo = listaProtocolli.get(key);
                if (protocollo.getDirezione().equalsIgnoreCase("entrata")) {
                    model.setValueAt(protocollo.getId(), rigaTabella, 0);
                    model.setValueAt(protocollo.getData(), rigaTabella, 1);
                    model.setValueAt(protocollo.getMittente(), rigaTabella, 2);
                    model.setValueAt(protocollo.getOggetto(), rigaTabella, 3);
                    model.setValueAt(protocollo.getMezzo(), rigaTabella, 4);
                    model.setValueAt("", rigaTabella, 5);
                    model.setValueAt("", rigaTabella, 6);
                    model.setValueAt("", rigaTabella, 7);
                    JButton pulsante = new JButton("Apri File");
                    pulsante.addActionListener(new ActionListener() {
    
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            if(protocollo.getFile().equals("") || protocollo.getFile() ==null)
                                JOptionPane.showMessageDialog(null, "File non presente");
                            else
                            launchFile(protocollo.getFile());
                        }
                    });
                    model.setValueAt(pulsante, rigaTabella, 8);
    
                } else {
    
                    model.setValueAt(protocollo.getId(), rigaTabella, 0);
                    model.setValueAt(protocollo.getData(), rigaTabella, 1);
                    model.setValueAt(protocollo.getMittente(), rigaTabella, 6);
                    model.setValueAt(protocollo.getOggetto(), rigaTabella, 5);
                    model.setValueAt(protocollo.getMezzo(), rigaTabella, 7);
                    model.setValueAt("", rigaTabella, 3);
                    model.setValueAt("", rigaTabella, 4);
                    model.setValueAt("", rigaTabella, 2);
                    JButton pulsante = new JButton("Apri File");
                    pulsante.addActionListener(new ActionListener() {
    
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            if(protocollo.getFile().equals("") || protocollo.getFile() ==null)
                                JOptionPane.showMessageDialog(null, "File non presente");
                            else
                            launchFile(protocollo.getFile());
                        }
                    });
                    model.setValueAt(pulsante, rigaTabella, 8);
                    rigaTabella++;
                }
                this.tabellaProtocollo.setModel(model);
            }
        }
    ma evidentemente non è così visto che mi restituisce un errore, esattamente questo:

    codice:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    	at graphicComponent.TableButtonRender.getTableCellRendererComponent(TableButtonRender.java:25)
    	at javax.swing.JTable.prepareRenderer(JTable.java:5735)
    	at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2114)
    	at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:2016)
    	at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1812)
    	at javax.swing.plaf.ComponentUI.update(ComponentUI.java:161)
    	at javax.swing.JComponent.paintComponent(JComponent.java:778)
    	at javax.swing.JComponent.paint(JComponent.java:1054)
    	at javax.swing.JComponent.paintChildren(JComponent.java:887)
    	at javax.swing.JComponent.paint(JComponent.java:1063)
    	at javax.swing.JViewport.paint(JViewport.java:725)
    	at javax.swing.JComponent.paintChildren(JComponent.java:887)
    	at javax.swing.JComponent.paint(JComponent.java:1063)
    	at javax.swing.JComponent.paintChildren(JComponent.java:887)
    	at javax.swing.JComponent.paint(JComponent.java:1063)
    	at javax.swing.JComponent.paintChildren(JComponent.java:887)
    	at javax.swing.JComponent.paint(JComponent.java:1063)
    	at javax.swing.JComponent.paintChildren(JComponent.java:887)
    	at javax.swing.JComponent.paint(JComponent.java:1063)
    	at javax.swing.JLayeredPane.paint(JLayeredPane.java:585)
    	at javax.swing.JComponent.paintChildren(JComponent.java:887)
    	at javax.swing.JComponent.paintToOffscreen(JComponent.java:5228)
    	at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(RepaintManager.java:1482)
    	at javax.swing.RepaintManager$PaintManager.paint(RepaintManager.java:1413)
    	at javax.swing.RepaintManager.paint(RepaintManager.java:1206)
    	at javax.swing.JComponent.paint(JComponent.java:1040)
    	at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:39)
    	at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:78)
    	at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:115)
    	at java.awt.Container.paint(Container.java:1967)
    	at java.awt.Window.paint(Window.java:3867)
    	at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:781)
    	at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:728)
    	at javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:677)
    	at javax.swing.RepaintManager.access$700(RepaintManager.java:59)
    	at javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1621)
    	at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
    	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:705)
    	at java.awt.EventQueue.access$000(EventQueue.java:101)
    	at java.awt.EventQueue$3.run(EventQueue.java:666)
    	at java.awt.EventQueue$3.run(EventQueue.java:664)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    	at java.awt.EventQueue.dispatchEvent(EventQueue.java:675)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
    	at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
    con il nullpointer che punta a questa riga

    codice:
            JButton renderButton = renderButtons.get(button.getText());

    ora, dove mi sono perso? salto qualche passaggio? sinceramente non ci sto capendo più niente anche perchè nel frattempo sto leggendo iText in Action 2.0 e sinceramente sto sbattendo anche lì X_X

  2. #2
    ma perché crei la classe TableButtonRender e la estendi con AbstractCellEditor invece che con JButton...?

    e comunque xche sicuramente value non è un tipo JButton...e quindi risulta non inizializzata...
    I computer sono incredibilmente veloci, accurati e stupidi.
    Gli uomini sono incredibilmente lenti, inaccurati e intelligenti.
    Insieme sono una potenza che supera l'immaginazione.

    A.Einstein

  3. #3
    guarda la mia classe di ButtonRenderer... che ho fatto per un progetto di "gestione campionato"

    a parte quel peccatuccio nel costruttore(dove avrei divuto fare un metodo get ma x fretta ho preferito far così) poi funziona

    codice:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
     
    /**
     * @version 1.0 11/09/98
     */
    public class ButtonRenderer extends JButton implements TableCellRenderer {
     
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	private boolean[] disp;
    	
    	public ButtonRenderer(MyInternalFrame _frame) {
        	setOpaque(true);
        	disp=_frame.disputata;
        	
      	}
      
    	public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    		
    		//System.out.println("Row:"+row+"\nColumn:"+ column);
    		//System.out.println();
    		if (isSelected) {
          		setForeground(table.getSelectionForeground());
          		setBackground(table.getSelectionBackground());
        	} 
        	else{
          		setForeground(table.getForeground());
          		setBackground(UIManager.getColor("Button.background"));
        	}
    	
    	
    		if(disp[row]){
    			setText("Giocata");
    			this.setEnabled(false);
    		}
        	//setText( (value ==null) ? "" : value.toString() );
    		else	{
    			setText("Calcola");
    			this.setEnabled(true);
    		}
        	return this;
      	}
    }
    I computer sono incredibilmente veloci, accurati e stupidi.
    Gli uomini sono incredibilmente lenti, inaccurati e intelligenti.
    Insieme sono una potenza che supera l'immaginazione.

    A.Einstein

  4. #4
    mmm in effetti non hai tutti i torti. il rpblema ora è che io devo associare ad ogni pulsante l'apertura di un nuovo file, sempre diverso ogni volta e che cambia dinamicamente.

    come gestiresti (in riferimento al fatto che tu hai in memoria un vettore di boolean)

  5. #5
    mmm ma il JButton ha qualche riferimento o qualcosa che lo accomuna al file creato?
    xche se non c'è nulla che li accomuna allora è facilissimo...

    P.S. un file vuoto?
    I computer sono incredibilmente veloci, accurati e stupidi.
    Gli uomini sono incredibilmente lenti, inaccurati e intelligenti.
    Insieme sono una potenza che supera l'immaginazione.

    A.Einstein

  6. #6
    però un'altra cosa...
    ho gestito una cosa del genere sempre nello stesso progetto
    con la Button Editor
    avevo 10 partite(della giornata) messe in un HashMap e poi me le sono gestite tutte

    codice:
    /**
     * @(#)ButtonEditor.java
     *
     *
     * @author 
     * @version 1.00 2010/1/10
     */
    
    
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Hashtable;
    /**
     * @version 1.0 11/09/98
     */
    public class ButtonEditor extends DefaultCellEditor {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	protected JButton button;
    	protected JLabel lab;
    	private String label;
      	private boolean isPushed;
     	private int _row;
     	private Hashtable<Integer, Risultato> matchs;
     	private Risultato r;
     	private DesktopFrame superForm;
     	private MyInternalFrame frame;
     
    	public ButtonEditor(JCheckBox checkBox, MyInternalFrame frame, DesktopFrame sf) {
        	super(checkBox);
        	superForm=sf;
        	matchs=new Hashtable<Integer, Risultato>();
        	try{
        		this.frame=frame;
       	    	r=null;
        	}
        	catch(Exception e){
        		e.printStackTrace();
        	}
        
        	button = new JButton();
        	button.setOpaque(true);
        	
        
        	button.addActionListener(new ActionListener() {
          		public void actionPerformed(ActionEvent e) {
    	        	fireEditingStopped();	        
    	        
    			}
        	}
        	);    	
        }
     
    	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    		
    		System.out.println();
        	if (isSelected) {
          		button.setForeground(table.getSelectionForeground());
          		button.setBackground(table.getSelectionBackground());
        	} 
        	else{
          		button.setForeground(table.getForeground());
          		button.setBackground(table.getBackground());
        	}
        	
        	label = "...";
        	button.setText( label );
        	_row=row;
        	isPushed = true;
        	return button;
    	}
     
      	public Object getCellEditorValue() {
        	if (isPushed)  {
        		for(int i=0; i<10; i++){
        			try{
        				
        				int risA=frame.getRisultatoA(i);
        				int risB=frame.getRisultatoB(i);
        				this.matchs.put(i, new Risultato(frame.getIdMatch(i), risA, risB));
        			}
        			catch(Exception e){
        				e.printStackTrace();
        			}
        		}
        		Object riga=(Object)_row;
        		r = (Risultato)matchs.get(riga);
        		
        		//JOptionPane.showMessageDialog(button ,"idpartita: "+r.getIdPartita());
        		modifyResult(r);
        	}
        	
        	if(AlreadyPlayed(r.getIdPartita())){
        		label = "Giocata";
        		button.setText( label );
      		}
        	else{
        		label = "Calcola";
            	button.setText( label );
        	}
        	isPushed = false;
        	return new String( label ) ;
    	}
       
      	public boolean stopCellEditing() {
        	isPushed = false;
        	return super.stopCellEditing();
      	}
     
    	protected void fireEditingStopped() {
        	super.fireEditingStopped();
      	}
    	
    	private boolean AlreadyPlayed(int idPartita){
    		boolean b;
    		LinkDB db=new LinkDB();
    		b=db.seePlayed(idPartita);
    		db.closeConnection();
    		return b;
    	}
      	
      	public void modifyResult(Risultato filmpartita){
      	     //qui chiamo le classi per la memorizzazione del risultato
                 //tu invece potresti aprirti il tuo file.....
      	}
    }
    I computer sono incredibilmente veloci, accurati e stupidi.
    Gli uomini sono incredibilmente lenti, inaccurati e intelligenti.
    Insieme sono una potenza che supera l'immaginazione.

    A.Einstein

  7. #7
    no ti spiego il tutto:

    ho questa tabella a 8 colonne, dove nei primi 7 campi ci sono dei dati "String", e nell'8 campo c'è il path ad un file. io ora voglio associare a questo campo un jbutton che mi apra autoamticamente il file che è stato precedentemente creato. ovviamente se in fase di creazione il campo path non è stato settato mi deve apparire il classico JOption.... "file assente"....

    in codice:
    codice:
                    JButton pulsante = new JButton("Apri File");
                    pulsante.addActionListener(new ActionListener() {
    
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            if(protocollo.getFile().equals("") || protocollo.getFile() ==null)
                                JOptionPane.showMessageDialog(null, "File non presente");
                            else
                            launchFile(protocollo.getFile());
                        }
                    });
    solo che non riesco a trasportare la meccanica sulla tabella e sul cellrender...starò affrontando il problema in senso sbagliato erchè concettualmente non mi pare nulla di complesso, ma non riesco proprio a scrivere il codice funzionante

  8. #8
    Originariamente inviato da schumy2000
    però un'altra cosa...
    ho gestito una cosa del genere sempre nello stesso progetto
    con la Button Editor
    avevo 10 partite(della giornata) messe in un HashMap e poi me le sono gestite tutte

    codice:
    /**
     * @(#)ButtonEditor.java
     *
     *
     * @author 
     * @version 1.00 2010/1/10
     */
    
    
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Hashtable;
    /**
     * @version 1.0 11/09/98
     */
    public class ButtonEditor extends DefaultCellEditor {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	protected JButton button;
    	protected JLabel lab;
    	private String label;
      	private boolean isPushed;
     	private int _row;
     	private Hashtable<Integer, Risultato> matchs;
    ....
    ...
    ..
    .
    }

    ecco anche qui tu "tieni traccia" degli oggetti attraverso una hashtable, ed è quesot passaggio che mi manca. me lo pieghi perpiacere? perchè ne tieni traccia, come ne tieni traccia e come "in automatico" lui sà come ricostruirlo.

  9. #9
    dopo vari tentativi ho risolto:

    codice:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package graphicComponent;
    
    import java.awt.Component;
    import java.awt.Desktop;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URI;
    import java.net.URISyntaxException;
    import java.net.URL;
    import java.util.Map;
    import java.util.WeakHashMap;
    import javax.swing.AbstractCellEditor;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JTable;
    import javax.swing.table.TableCellEditor;
    
    /**
     *
     * @author Utente1
     */
    public class ButtonEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
    
        private JButton pulsante;
        private String path;
    
        public ButtonEditor() {
            pulsante = new JButton("Lancia File!");
            pulsante.addActionListener(this);
        }
    
        @Override
        public Object getCellEditorValue() {
            return path;
        }
    
        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            path = (String) value;
            if (path.equalsIgnoreCase("") || path.equalsIgnoreCase(" ")) {
                JOptionPane.showMessageDialog(null, "Nessun File Associato", "Errore apertura file", JOptionPane.ERROR_MESSAGE);
            }
            return pulsante;
        }
    
        private URI getFileURI(String filePath) {
            URI uri = null;
            filePath = filePath.trim();
            if (filePath.indexOf("http") == 0 || filePath.indexOf("\\") == 0) {
                if (filePath.indexOf("\\") == 0) {
                    filePath = "file:" + filePath;
                    filePath = filePath.replaceAll("#", "%23");
                }
                try {
                    filePath = filePath.replaceAll(" ", "%20");
                    URL url = new URL(filePath);
                    uri = url.toURI();
                } catch (MalformedURLException ex) {
                    ex.printStackTrace();
                } catch (URISyntaxException ex) {
                    ex.printStackTrace();
                }
            } else {
                File file = new File(filePath);
                uri = file.toURI();
            }
            return uri;
        }
    
        public void launchFile(File file) {
            if (!Desktop.isDesktopSupported()) {
                return;
            }
            Desktop dt = Desktop.getDesktop();
            try {
                dt.open(file);
            } catch (IOException ex) {
                launchFile(file.getPath());
            }
        }
    
        public void launchFile(String filePath) {
            if (filePath == null || filePath.trim().length() == 0) {
                return;
            }
            if (!Desktop.isDesktopSupported()) {
                return;
            }
            Desktop dt = Desktop.getDesktop();
            try {
                dt.browse(getFileURI(filePath));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            launchFile(path);
        }
    }
    codice:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package graphicComponent;
    
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    
    /**
     * @version 1.0 11/09/98
     */
    public class ButtonRender extends JButton implements TableCellRenderer {
    
        /**
         *
         */
        private static final long serialVersionUID = 1L;
    
        public ButtonRender() {
            super();
            setOpaque(true);
    
        }
    
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            if (isSelected) {
                setForeground(table.getSelectionForeground());
                setBackground(table.getSelectionBackground());
            } else {
                setForeground(table.getForeground());
                setBackground(UIManager.getColor("Button.background"));
            }
            setText("Lancia File");
            this.setEnabled(true);
            return this;
        }
    }
    per chiuque dovesse utilizzarlo in futuro.

  10. #10
    Infatti nel Buttonrenderer la visualizzazione del Button come icona.
    Nel ButtonEditor invece performi il comportamento....
    spero di averti dato la scintilla per il quale tu abbia capito come sviluppare
    I computer sono incredibilmente veloci, accurati e stupidi.
    Gli uomini sono incredibilmente lenti, inaccurati e intelligenti.
    Insieme sono una potenza che supera l'immaginazione.

    A.Einstein

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.