jFrame frozen / hung when opened in a jTable

2

The idea is to click on the line of the table that is a jFrame1 and open another jFrame2 with the search of the information of the person based on RE, but when I click on it the code until it works but opens the frozen and locked window.

The code for listing in jTable1 is this:

public void PesquisarFuncionarios() {
    txtBusca.requestFocus();
    ArrayList dados = new ArrayList();
    String[] Colunas = new String[] {
        "RE/MAT", "NOME", "FUNÇÃO"
    };

    String sql = "Select REMAT,NOME,FUNCAO from funcionarios where NOME like ?";
    try {
        pst = con.prepareStatement(sql);
        pst.setString(1, txtBusca.getText() + "%");
        rs = pst.executeQuery();

        while (rs.next()) {
            dados.add(new Object[] {
                rs.getString("REMAT"), rs.getString("NOME"), rs.getString("FUNCAO")
            });
        }
    } catch (SQLException error) {
        JOptionPane.showMessageDialog(null, "ERRO AO PESQUISAR" + error);
    }

    Listar modelo = new Listar(dados, Colunas);
    jListar.setModel(modelo);
    jListar.getColumnModel().getColumn(0).setPreferredWidth(80);
    jListar.getColumnModel().getColumn(0).setResizable(false);

    jListar.getColumnModel().getColumn(1).setPreferredWidth(350);
    jListar.getColumnModel().getColumn(1).setResizable(false);

    jListar.getColumnModel().getColumn(2).setPreferredWidth(400);
    jListar.getColumnModel().getColumn(2).setResizable(false);

    jListar.getTableHeader().setReorderingAllowed(false);
    jListar.setAutoResizeMode(jListar.AUTO_RESIZE_OFF);
    jListar.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}

public void BuscarLinhas() {
    int selecionada = jListar.getSelectedRow();
    if (selecionada == -1) {
        return; //Não tem nada selecionado
    }
    setRemat(Integer.parseInt(jListar.getValueAt(selecionada, 0).toString()));
}

But now in the other jframe2 does not have any code, but when it calls it to open with the variable of the RE it locks and has to close finishing the execute.

The entire jFrame1:

package atestados;

import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.*;
import java.util.*;
import atestados.mysql;

import javax.swing.*;

/**
 *
 * @author FU14855
*/


 public class Consultar extends javax.swing.JFrame {



Connection con;
PreparedStatement pst;
ResultSet rs;
private int remat;

/**
 * Creates new form Consultar
 */
     public Consultar() throws 
  ClassNotFoundException, 
 InstantiationException, 
 IllegalAccessException {

     initComponents();
     setResizable(false);
    setLocationRelativeTo(null);//iniciar a tela no centro do monitor
    con = mysql.abrirConexao();
    PesquisarFuncionarios();
}

Consultar(CONSULTAS aThis, boolean b) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body      of generated methods, choose Tools | Templates.
}


public void PesquisarFuncionarios() {
    txtBusca.requestFocus();
    ArrayList dados = new ArrayList();
    String[] Colunas = new String[]{"RE/MAT", "NOME", "FUNÇÃO"};

    String sql = "Select REMAT,NOME,FUNCAO from funcionarios where NOME like ?";
    try {
        pst = con.prepareStatement(sql);
        pst.setString(1, txtBusca.getText() + "%");
        rs = pst.executeQuery();

        while (rs.next()) {
            dados.add(new Object[]{rs.getString("REMAT"), 
   rs.getString("NOME"), rs.getString("FUNCAO")});

        }

    } catch (SQLException error) {
        JOptionPane.showMessageDialog(null, "ERRO AO PESQUISAR" + error);

    }
    Listar modelo = new Listar(dados, Colunas);
    jListar.setModel(modelo);
    jListar.getColumnModel().getColumn(0).setPreferredWidth(80);
    jListar.getColumnModel().getColumn(0).setResizable(false);

    jListar.getColumnModel().getColumn(1).setPreferredWidth(350);
    jListar.getColumnModel().getColumn(1).setResizable(false);

    jListar.getColumnModel().getColumn(2).setPreferredWidth(400);
    jListar.getColumnModel().getColumn(2).setResizable(false);

    jListar.getTableHeader().setReorderingAllowed(false);
    jListar.setAutoResizeMode(jListar.AUTO_RESIZE_OFF);
    jListar.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

}

public void BuscarLinhas() {

    int selecionada = jListar.getSelectedRow();
    if (selecionada == -1) {
        return; //Não tem nada selecionado
    }
    setRemat(Integer.parseInt(jListar.getValueAt(selecionada, 0).toString()));

  //  System.out.println(getRemat());

}
public void ConsultarCad(String cid){
            CONSULTAS menuzin = new CONSULTAS(cid);
       this.dispose();
            menuzin.setVisible(true);

 }

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    jButton1 = new javax.swing.JButton();
    txtBusca = new javax.swing.JTextField();
    jButton2 = new javax.swing.JButton();
    jScrollPane2 = new javax.swing.JScrollPane();
    jListar = new javax.swing.JTable();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("CONSULTAR");

    jLabel1.setText("LOCALIZE O FUNCIONÁRIO PELO NOME:");

    jButton1.setText("CADASTRAR NOVO(A) FUNCIONARIO");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    txtBusca.setFocusCycleRoot(true);
    txtBusca.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyReleased(java.awt.event.KeyEvent evt) {
            txtBuscaKeyReleased(evt);
        }
    });

    jButton2.setText("VOLTAR");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    jListar.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null}
        },
        new String [] {
            "Title 1", "Title 2", "Title 3", "Title 4"
        }
    ));
    jListar.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jListarMouseClicked(evt);
        }
        public void mouseReleased(java.awt.event.MouseEvent evt) {
            jListarMouseReleased(evt);
        }
    });
    jScrollPane2.setViewportView(jListar);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.
     Alignment.TRAILING,layout.createSequentialGroup()
            .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(jScrollPane2)
                .addComponent(txtBusca, javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.
  Alignment.LEADING,layout.createSequentialGroup()
                    .addComponent(jLabel1)
           .addPreferredGap(javax.swing.LayoutStyle.
   ComponentPlacement.RELATED,389, Short.MAX_VALUE)
                    .addComponent(jButton1))
   .addGroup(javax.swing.GroupLayout.Alignment.LEADING,layout.createSequentialGroup()
                    .addComponent(jButton2)
                    .addGap(0, 0, Short.MAX_VALUE)))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jButton2)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(jButton1))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(txtBusca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 513, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
    );

    pack();
}// </editor-fold>                        

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    cadastro cada = null;
    try {
        cada = new cadastro();
    } catch (InstantiationException ex) {
        Logger.getLogger(Consultar.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(Consultar.class.getName()).log(Level.SEVERE, null, ex);
    }

    cada.show();
    setVisible(false);


}                                        

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    TelaAcesso tela = new TelaAcesso();

    tela.show();
    setVisible(false);
}                                        

private void txtBuscaKeyReleased(java.awt.event.KeyEvent evt) {                                     
    PesquisarFuncionarios();

}                                    

private void jListarMouseReleased(java.awt.event.MouseEvent evt) {                                      


}                                     

private void jListarMouseClicked(java.awt.event.MouseEvent evt) {                                     
    BuscarLinhas();
    ConsultarCad(String.valueOf(getRemat()));

}                                    

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Consultar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Consultar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Consultar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  java.util.logging.Logger.getLogger(Consultar.class.getName()).log(java.util.logging.Level            .SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(() -> {
        try {
            new Consultar().setVisible(true);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Consultar.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(Consultar.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(Consultar.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JTable jListar;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextField txtBusca;
// End of variables declaration                   

/**
 * @return the remat
 */
public int getRemat() {
    return remat;
}

/**
 * @param remat the remat to set
 */
public void setRemat(int remat) {
    this.remat = remat;
}


/**
 * @return the remat
 */



  }
    
asked by anonymous 30.01.2015 / 13:58

1 answer

1

Vinicius , so I understand what's happening in your code:

The jFrame1 is running in a thread specific, you then search and create a list of data and then move to jFrame2 .

However jFrame2 is in another thread when it is displaying, and when it receives the list, it receives the reference from that list created in jFrame1 . From there you have two threads trying to use the data list, which probably causes the window to crash.

SOLUTION

Change the jFrame2 by a JDialog and set the mode to true.

 JDialog dialog = new JDialog(parent, true);

Or you create a class that extends JFrame and when you send the list to jFrame2 , you create a copy of the list within jFrame2 before displaying it. Something like this:

private void abrirDadosNoJFrame2(List dados){
      JFrameExtendido jFrame2 = new JFrameExtendido(dados);
      jFrame2.setVisible(true);
}

In the JFrameExtendido constructor:

private List listaDados;

public JFrameExtendido(List dados){
      initComponents();
      listaDados = new ArrayList(dados);
}
    
07.07.2015 / 17:53