Erro na classe EventdispatchThread ao tentar utilizar a classe ButtonColumn para um Jtable

0 respostas
lary_nascimento

Olá pessoal.
Estou usando a classe ButtonColumn que encontrei aqui no site para inserir um botão dentro de uma célula do Jtable.
Personalizei para se adequar ao que eu preciso... assim ficou:

class ButtonColumn extends AbstractCellEditor
        implements TableCellRenderer, TableCellEditor, ActionListener {

    JTable table;
    JButton renderButton;
    JButton editButton;
    String text;
    int index = 0;
    String cod_selo = "";
    int countFiles;
    String[] files = new String[999];
    byte[] anexo = new byte[0];

    public ButtonColumn(JTable table, int column) {
        super();
        this.table = table;
        renderButton = new JButton();

        editButton = new JButton();
        setFocusPainted(false);
        editButton.addActionListener(this);

        TableColumnModel columnModel = table.getColumnModel();
        columnModel.getColumn(column).setCellRenderer(this);
        columnModel.getColumn(column).setCellEditor(this);
    }

    public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        if (hasFocus) {
            renderButton.setForeground(table.getForeground());
            renderButton.setBackground(UIManager.getColor("Button.background"));
        } else if (isSelected) {
            renderButton.setForeground(table.getSelectionForeground());
            renderButton.setBackground(table.getSelectionBackground());
        } else {
            renderButton.setForeground(table.getForeground());
            renderButton.setBackground(UIManager.getColor("Button.background"));
        }

        renderButton.setText("Anexo");
        return renderButton;
    }

    public Component getTableCellEditorComponent(
            JTable table, Object value, boolean isSelected, int row, int column) {
        
        editButton.setText("Anexo");
    return editButton;
       
    }

    public Object getCellEditorValue() {
        return text;
    }
    ArrayList<HashMap<String, Object>> arli = new ArrayList<HashMap<String, Object>>();

    protected void CarregaDados() throws SQLException {
        conexao conn = new conexao();
        conn.conecta();
        conn.executeSQL("Select cod_selo,anexo,extensao from Veiculos where cod_selo=" + cod_selo);
        arli.clear();
        while (conn.resultset.next()) {
            HashMap<String, Object> mapa = new HashMap<String, Object>();
            for (String nomeCampo : GetNomesCampos()) {
                mapa.put(nomeCampo, conn.resultset.getObject(nomeCampo));
            }
            arli.add(mapa);
        }
    }

    protected HashMap<String, Object> Atual() {
        if (arli.isEmpty()) {
            return null;
        } else {
            return (HashMap<String, Object>) arli.get(index);
           
        }
    }

    protected HashMap<String, Object> GetDados() {
        HashMap<String, Object> dados = new HashMap<String, Object>();

        dados.put("cod_selo", Valor("cod_selo"));


        dados.put("anexo", Valor("anexo"));

        dados.put("extensao", Valor("extensao"));

        return dados;


    }

    protected Object Valor(String key) {
        try {
            return Atual().get(key);
        } catch (Exception ex) {
            return 0;
        }
    }

    private ArrayList<String> GetNomesCampos() {
        ArrayList<String> retorno = new ArrayList<String>();
        HashMap<String, Object> dados = GetDados();

        ArrayList<Entry<String, Object>> lista = new ArrayList<Entry<String, Object>>(dados.entrySet());
        for (Entry<String, Object> dado : lista) {
            retorno.add(dado.getKey());
        }
        return retorno;
    }

    public void actionPerformed(ActionEvent e) {
        String fileAtual = "";
        String fileAtualVetor = "";
        conexao conn = new conexao();
        conn.conecta();
        int co = table.getSelectedRow();
        cod_selo = (table.getValueAt(co, 0).toString());

        String extensaofile = Atual().get("extensao").toString();
        anexo = (byte[]) Valor("anexo");

        if (".jpg".equals(extensaofile)) {
            extensaofile = ".png";
        }

        File file = new File("C:\\Temp\\Arquivo Temporario - Cadastr. Veíc. IASP" + extensaofile); //Criamos um nome para o arquivo  

        for (int i = 0; i <= countFiles; i++) {
            //se o vetor ainda não for preenchido, ou seja, se for o primeiro índice, 
            //eu adiciono o primeiro file no vetor e somo o contador de files(que é o índice do vetor) e quebro o for
            if (files[0] == null) {

                files[0] = file.toString();
                countFiles++;
                break;
            } else {
                fileAtual = file.toString();
                fileAtualVetor = files[i];

                //se a posição atual no vetor estiver vazia, 
                //atribui-se vazio em string, para que não dê erro na comparação em seguida
                if (fileAtualVetor == null) {
                    fileAtualVetor = "";
                }
                // se o arquivo atual que está no vetor for igual ao file que está sendo aberto no momento, 
                //quebra o laço, pois se inserir um filme igual a um existente no vetor, dará erro na hora de excluir.
                if (fileAtualVetor.equals(fileAtual)) {
                    break;

                    // depois de todas as comparações para verificar se o arquivo já não foi aberto e inserido no vetor, 
                    // se não tiver sido inserido e for a ultima posição do vetor, insere-se o arquivo no vetor
                } else if (i == countFiles) {
                    files[countFiles] = file.toString();
                    countFiles++;
                    break;
                }
            }

        }
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(file)); //Criamos o arquivo
            bos.write(anexo); //Gravamos os bytes lá
            bos.close(); //Fechamos o stream. 

        } catch (FileNotFoundException ex) {
            Logger.getLogger(CadastroVeiculos.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, "Arquivo não encontrado", "OPS!", JOptionPane.WARNING_MESSAGE);


        } catch (IOException ex) {
            Logger.getLogger(CadastroVeiculos.class.getName()).log(Level.SEVERE, null, ex);
        }



        try {
            Desktop.getDesktop().open(file);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Erro no Desktop: " + ex, "Erro!", JOptionPane.ERROR_MESSAGE);

        }
    }

   
}

Porém el dá erro nesta parte na hora de retornar o editButton:

public Component getTableCellEditorComponent(
            JTable table, Object value, boolean isSelected, int row, int column) {
        
        editButton.setText("Anexo");
    return editButton;
       
    }

e para neste ponto(while) na classe eventdispatchThread:

void pumpEventsForFilter(int id, Conditional cond, EventFilter filter) {
        addEventFilter(filter);
        doDispatch = true;
        while (doDispatch && !isInterrupted() && cond.evaluate()) {
            pumpOneEventForFilters(id);
        }
        removeEventFilter(filter);
    }

Eu não faço a mínima ideia do que pode estar acontecendo.
Agradeço MUITO a ajuda.

Criado 27 de junho de 2013
Respostas 0
Participantes 1