Inserire JButton in una cella di una JTable

di il
1 risposte

Inserire JButton in una cella di una JTable

Il tutorial oracle (http://docs.oracle.com/javase/tutorial/uiswing/components/table.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:

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:
    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();

[B]        TableColumn column = this.tabellaProtocollo.getColumnModel().getColumn(8);
        TableButtonRender render=new TableButtonRender();
        column.setCellRenderer(render);
[/B]

        ((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:
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
        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

1 Risposte

  • Re: Inserire JButton in una cella di una JTable

    Dopo vari tentativi ho risolto:
    
    /*
     * 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);
        }
    }
    
    
    
    /*
     * 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.
Devi accedere o registrarti per scrivere nel forum
1 risposte