Problemas com Evento MouseCliked

5 respostas
Douglas_Rafael

Ok, esses são os métodos “preencherTabela” e “jTableListarUsuariosCadastradosMouseClicked”

public void preencherTabela(String sql){
    ArrayList dados  = new ArrayList();
    String[] colunas = new String[] {"Id","Usuario","Tipo","Senha"};
            
    conex.conectarPostgre();
    conex.executarSql(sql);
    
    try {
        conex.rs.first();
        
        do{
            dados.add(new Object[]{conex.rs.getInt("codigo_usuario"),conex.rs.getString("nome_usuario"), conex.rs.getString("tipo_usuario"), conex.rs.getString("senha_usuario")});
        }while(conex.rs.next());
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(rootPane, "Busco por outro Usuário para preencher Tabela! " + ex);
    }
    ModeloTabela modelousuario = new ModeloTabela(dados, colunas);
    
    jTableListarUsuariosCadastrados.setModel(modelousuario);
    jTableListarUsuariosCadastrados.getColumnModel().getColumn(0).setPreferredWidth(2);
    jTableListarUsuariosCadastrados.getColumnModel().getColumn(0).getResizable();
    jTableListarUsuariosCadastrados.getColumnModel().getColumn(1).setPreferredWidth(180);
    jTableListarUsuariosCadastrados.getColumnModel().getColumn(1).getResizable();
    jTableListarUsuariosCadastrados.getColumnModel().getColumn(2).setPreferredWidth(180);
    jTableListarUsuariosCadastrados.getColumnModel().getColumn(2).getResizable();
    
    jTableListarUsuariosCadastrados.getColumnModel().getColumn(3).setPreferredWidth(8);
    jTableListarUsuariosCadastrados.getColumnModel().getColumn(3).getResizable();
    

    jTableListarUsuariosCadastrados.getTableHeader().setReorderingAllowed(false);
    
    //jTableListarUsuariosCadastrados.setAutoResizeMode(jTableListarUsuariosCadastrados.AUTO_RESIZE_ALL_COLUMNS);
    
    jTableListarUsuariosCadastrados.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    
    conex.desconectar();
}

private void jTableListarUsuariosCadastradosMouseClicked(java.awt.event.MouseEvent evt) {                                                             
    // TODO add your handling code here:
    String nome_usuario =""+jTableListarUsuariosCadastrados.getValueAt(jTableListarUsuariosCadastrados.getSelectedRow(), 1);
    
    conex.conectarPostgre();
    
    conex.executarSql("select * from usuario where nome_usuario='"+nome_usuario+"'");
    try {
        conex.rs.first();
        
        jTextFieldCodigoUsuario.setText(String.valueOf(conex.rs.getInt("codigo_usuario")));
        jTextFieldUsuCadUsu.setText(conex.rs.getString("nome_usuario"));
        jComboBoxTipoCadUsu.setSelectedItem(conex.rs.getString("tipo_usuario"));
        jPasswordFieldSenCadUsu.setText(conex.rs.getString("senha_usuario"));
        jPasswordFieldConfSenCadUsu.setText(conex.rs.getString("senha_usuario"));
            
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, "Erro ao selecionar dados do Usuário! "+ex);
    }
    conex.desconectar();
    jButtonEdiCadUsu.setEnabled(true);
    jButtonExcCadUsu.setEnabled(true);
}

Essa é minha tela do usuário.

O MEU PROBLEMA é que quando eu tento clicar em algum nome nessa tabela, ela me retorna esse erro. Já tentei de várias maneiras resolver, mas nada…
Alguém pra me ajudar?

O erro que extoura:

run:
Exception in thread AWT-EventQueue-0 java.lang.ArrayIndexOutOfBoundsException: -1

at java.util.ArrayList.elementData(ArrayList.java:418)

at java.util.ArrayList.get(ArrayList.java:431)

at modeloBeans.ModeloTabela.getValueAt(ModeloTabela.java:48)

at javax.swing.JTable.getValueAt(JTable.java:2717)

at visao.FormUsuario.jTableListarUsuariosCadastradosMouseClicked(FormUsuario.java:573)

at visao.FormUsuario.access$400(FormUsuario.java:23)

at visao.FormUsuario$5.mouseClicked(FormUsuario.java:140)

at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:270)

at java.awt.Component.processMouseEvent(Component.java:6536)

at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)

at java.awt.Component.processEvent(Component.java:6298)

at java.awt.Container.processEvent(Container.java:2236)

at java.awt.Component.dispatchEventImpl(Component.java:4889)

at java.awt.Container.dispatchEventImpl(Container.java:2294)

at java.awt.Component.dispatchEvent(Component.java:4711)

at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)

at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4534)

at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)

at java.awt.Container.dispatchEventImpl(Container.java:2280)

at java.awt.Window.dispatchEventImpl(Window.java:2746)

at java.awt.Component.dispatchEvent(Component.java:4711)

at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)

at java.awt.EventQueue.access$500(EventQueue.java:97)

at java.awt.EventQueue$3.run(EventQueue.java:709)

at java.awt.EventQueue$3.run(EventQueue.java:703)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)

at java.awt.EventQueue$4.run(EventQueue.java:731)

at java.awt.EventQueue$4.run(EventQueue.java:729)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)

at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)

at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)

at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)

at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

5 Respostas

staroski

É que não há nenhuma linha selecionada na sua JTable, aí o jTableListarUsuariosCadastrados.getSelectedRow() retorna -1, aí quando você faz o jTableListarUsuariosCadastrados.getValueAt(-1, 1), ocorre exceção.

Uma pergunta, qual o motivo de você concatenar uma String vazia na linha abaixo?
String nome_usuario = "" + jTableListarUsuariosCadastrados.getValueAt(jTableListarUsuariosCadastrados.getSelectedRow(), 1);

Douglas_Rafael

“Uma pergunta, qual o motivo de você concatenar uma String vazia na linha abaixo?”

Pegar os dados da tabela e salvar nessa String

H

usa jTableListarUsuariosCadastrados.isSelected() dentro do if, antes de chamar o método de salvar, ou você pode garantir que 1 está selecionado usando o jTableListarUsuariosCadastrados.setSelected() antes de mostrar pro usuário.

Douglas_Rafael

Cara, consegui resolver de outra forma, mas muito obrigado pela ajuda. :smiley:

Douglas_Rafael

Consegui resolver de outra forma, mas muito obrigado pela ajuda. :smile:

Criado 1 de fevereiro de 2018
Ultima resposta 18 de abr. de 2018
Respostas 5
Participantes 3