jFrame frozen/locked when opening in a jTable

Asked

Viewed 692 times

2

The idea is to click on the row 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 works but opens the window frozen and locked.

The code for listing on 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 there is no code, but when you call it to open with the RE variable it hangs and has to close finishing the run.

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
 */



  }
  • Where is the JFrame in that code?

  • That’s the way it says in jFrame, I’ll post it in one piece

  • it is not your query in the 2nd jframe that is locking the JVM?

  • Do not perform I/O or network operations on the EDT! http://answall.com/a/2095/132

1 answer

1

Vinicius, from what I understand from your code what is happening is the following:

The jFrame1 is being executed in a thread specific, you then do a search and create a data list and then pass to the jFrame2.

But the jFrame2 is in another thread when displaying, and when receiving the list, it receives the reference of that list created in the jFrame1. From there you have two threads trying to use the data list, which probably leads to window locking.

SOLUTION

Exchange the jFrame2 by a JDialog and arrow the mode as true.

 JDialog dialog = new JDialog(parent, true);

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

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

In the builder of JFrameExtendido:

private List listaDados;

public JFrameExtendido(List dados){
      initComponents();
      listaDados = new ArrayList(dados);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.