Duvida sobre tratamento de botão

5 respostas
R

Boa tarde Pessoal…

Estou com um problema: Eu estou desenvolvendo uma aplicação tipo um controle de estoque.
Na Tela de cadastro de vendedores eu tenho botões de novo, alterar, gravar, excluir e sair. Eu quero fazer com que, quando a tela for chamada, apenas os botões de novo, e sair sejam hailitados e os outros fiquem desabilitados, e quando gravar os dados os outros botoes habilitem, não entendo a parte de eventos to começando agora no java , se alguém puder me ajudar ficarei muito grato.

Será se alguém pode me ajudar nesse problema. Pois eu não sei como tratar esses eventos do mouse.

OBS: ai está o código da tela de usuarios.

package cadastros;

import java.awt.Dialog;

import java.sql.SQLException;

import javax.swing.JOptionPane;

import classes.conexao;

import javax.swing.*;

import javax.swing.table.DefaultTableModel;

/**
*

  • @author Robson Vieira de Araújo
    /
    public class cad_usuario extends javax.swing.JFrame {
    conexao con_usuarios;
    private String ordencao; // Ordena no Jtable
    String ordem = “nome”;
    private String Ordena;
    /
    * Creates new form cad_usuario */
    public cad_usuario() {
    initComponents();
    setResizable(false);
    //-------CÓDIGO PARA REALIZAR CONEXAO COM A TABELA USUARIOS NO BANCO----------//
    con_usuarios = new conexao();
    con_usuarios.conecta();
    con_usuarios.executeSQL("select * from usuarios order by "+ordem);
    //—FINAL DO CÓDIGO PARA REALIZAR CONEXAO COM A TABELA USUARIOS NO BANCO-----//
// ------INICIO DO CÓDIGO PARA TRAZER OS DADOS DA TABELA USUARIOS-------------//

try

{

con_usuarios.resultset.first();

tf_codigo.setText(con_usuarios.resultset.getString(codigo));

tf_nome.setText(con_usuarios.resultset.getString(nome));

tf_caixa.setText(con_usuarios.resultset.getString(caixa));

tf_senha.setText(con_usuarios.resultset.getString(senha));
}
    catch(SQLException erro)
    
 {
     JOptionPane.showMessageDialog(null, "não localizou dados"+erro);
   }
    preencher_jtable(); // Chama método para preencher o JTable.
}

// -------FINAL DO CÓDIGO PARA TRAZER OS DADOS DA TABELA USUARIOS-------------//

/** 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() {

    grupo_ordem = new javax.swing.ButtonGroup();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();
    tf_codigo = new javax.swing.JTextField();
    tf_nome = new javax.swing.JTextField();
    tf_caixa = new javax.swing.JTextField();
    tf_senha = new javax.swing.JPasswordField();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    botao_novo = new javax.swing.JButton();
    botao_alterar = new javax.swing.JButton();
    botao_gravar = new javax.swing.JButton();
    botao_excluir = new javax.swing.JButton();
    botao_sair = new javax.swing.JButton();
    jButton1 = new javax.swing.JButton();
    jPanel1 = new javax.swing.JPanel();
    jRadioButton1 = new javax.swing.JRadioButton();
    jRadioButton2 = new javax.swing.JRadioButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Cadastro de Usuários/Atendentes");

    jLabel1.setText("Código.:");

    jLabel2.setText("Nome.:");

    jLabel3.setText("Nº Caixa.:");

    jLabel4.setText("Senha.:");

    tf_codigo.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            tf_codigoActionPerformed(evt);
        }
    });

    tf_nome.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            tf_nomeActionPerformed(evt);
        }
    });

    jTable1.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null}
        },
        new String [] {
            "Código", "Nome", "Caixa"
        }
    ) {
        boolean[] canEdit = new boolean [] {
            false, true, true
        };

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mousePressed(java.awt.event.MouseEvent evt) {
            jTable1MousePressed(evt);
        }
    });
    jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            jTable1KeyPressed(evt);
        }
        public void keyReleased(java.awt.event.KeyEvent evt) {
            jTable1KeyReleased(evt);
        }
    });
    jScrollPane1.setViewportView(jTable1);

    botao_novo.setFont(new java.awt.Font("Arial", 0, 11));
    botao_novo.setText("Novo");
    botao_novo.setToolTipText("Clique aqui para criar um novo registro");
    botao_novo.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            botao_novoActionPerformed(evt);
        }
    });

    botao_alterar.setFont(new java.awt.Font("Arial", 0, 11));
    botao_alterar.setText("Alterar");
    botao_alterar.setToolTipText("clique aqui para alterar o registro");
    botao_alterar.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            botao_alterarActionPerformed(evt);
        }
    });

    botao_gravar.setFont(new java.awt.Font("Arial", 0, 11));
    botao_gravar.setText("Gravar");
    botao_gravar.setToolTipText("clique aqui para gravar o registro");
    botao_gravar.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            botao_gravarActionPerformed(evt);
        }
    });

    botao_excluir.setFont(new java.awt.Font("Arial", 0, 11));
    botao_excluir.setText("Excluir");
    botao_excluir.setToolTipText("clique aqui para excluir o registro");
    botao_excluir.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            botao_excluirActionPerformed(evt);
        }
    });

    botao_sair.setFont(new java.awt.Font("Arial", 0, 11));
    botao_sair.setText("Sair");
    botao_sair.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            botao_sairActionPerformed(evt);
        }
    });

    jButton1.setFont(new java.awt.Font("Arial", 0, 11));
    jButton1.setText("Listar na Grade");
    jButton1.setToolTipText("clique aqui para filtrar os dados na tabela");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Ordenação", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 0, 11))); // NOI18N

    grupo_ordem.add(jRadioButton1);
    jRadioButton1.setFont(new java.awt.Font("Arial", 0, 11));
    jRadioButton1.setText("Código");
    jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jRadioButton1ActionPerformed(evt);
        }
    });

    grupo_ordem.add(jRadioButton2);
    jRadioButton2.setFont(new java.awt.Font("Arial", 0, 11));
    jRadioButton2.setSelected(true);
    jRadioButton2.setText("Nome");
    jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jRadioButton2ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jRadioButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jRadioButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap(12, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addComponent(jRadioButton1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jRadioButton2)
            .addContainerGap(8, Short.MAX_VALUE))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(botao_novo, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(botao_alterar)
                            .addGap(18, 18, 18)
                            .addComponent(botao_gravar)
                            .addGap(18, 18, 18)
                            .addComponent(botao_excluir, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(botao_sair, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jButton1)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 422, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(10, Short.MAX_VALUE))
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1)
                                .addComponent(jLabel2))
                            .addGap(18, 18, 18)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(tf_nome, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(tf_codigo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel3)
                                .addComponent(jLabel4))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(tf_senha, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(tf_caixa, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 80, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18))))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(tf_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(tf_nome, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(tf_caixa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4)
                        .addComponent(tf_senha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jButton1))
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(2, 2, 2)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(botao_alterar)
                .addComponent(botao_novo)
                .addComponent(botao_gravar)
                .addComponent(botao_excluir)
                .addComponent(botao_sair))
            .addContainerGap(15, Short.MAX_VALUE))
    );

    java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    setBounds((screenSize.width-450)/2, (screenSize.height-410)/2, 450, 410);
}// </editor-fold>
private void tf_codigoActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

}
private void botao_novoActionPerformed(java.awt.event.ActionEvent evt) {

//------------INICIO DO CÓDIGO PARA GERAR NOVO REGISTRO DE USUÁRIOS-----------//

tf_codigo.setText("");

tf_nome.setText("");

tf_caixa.setText("");

tf_senha.setText("");

tf_nome.requestFocus();

tf_codigo.setEditable(false);

}

//------------FINAL DO CÓDIGO PARA GERAR NOVO REGISTRO DE USUÁRIOS-----------//
private void botao_sairActionPerformed(java.awt.event.ActionEvent evt) {

dispose();

}
private void botao_gravarActionPerformed(java.awt.event.ActionEvent evt) {

//------------------INICIO DO CÓDIGO PARA GRAVAR DADOS DOS USUARIOS----------//

try

{

String sqlinsert =insert into usuarios (nome,caixa,senha) values (’”+

tf_nome.getText()+"’,’"+

tf_caixa.getText()+"’,’"+

tf_senha.getText()+"’)";

con_usuarios.statement.executeUpdate(sqlinsert);

JOptionPane.showMessageDialog(null, Gravação realizada com sucesso !);
// Atualiza o ResultSet.
       con_usuarios.executeSQL("Select * from usuarios ");
       con_usuarios.resultset.first(); // se posiciona no primeiro registro.
       mostrar_dados();
       preencher_jtable();
//------------INICIO DO CÓDIGO PARA LIMPAR OS CAMPOS DO FORM USUÁRIOS---------//

tf_codigo.setText("");

tf_nome.setText("");

tf_caixa.setText("");

tf_senha.setText("");
//------------FINAL DO CÓDIGO PARA LIMPAR OS CAMPOS DO FORM USUÁRIOS---------//

}

catch (SQLException erro)

{

JOptionPane.showMessageDialog(null, Erro ao tentar gravar o registro+erro);

}

//------------------FINAL DO CÓDIGO PARA GRAVAR DADOS DOS USUARIOS------------//

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

con_usuarios.executeSQL(select * from usuarios where nome like '”+tf_nome.getText()+"%’ order by " +ordencao);

preencher_jtable();

}
private void botao_excluirActionPerformed(java.awt.event.ActionEvent evt) {

try//------INICIO DO CÓDIGO PARA EXCLUIR OS USUÁRIOS DO FORM USUARIOS---------//

{

String sql = "select * from usuarios Where codigo = "+tf_codigo.getText();

con_usuarios.executeSQL(sql);

con_usuarios.resultset.first();

String nome = Deletar o Usuário: +con_usuarios.resultset.getString(nome)+ ?;

int opcao_escolhida = JOptionPane.showConfirmDialog(null,nome,"Exclusão ",JOptionPane.YES_NO_OPTION);

if (opcao_escolhida == JOptionPane.YES_OPTION)

{

sql = DELETE FROM usuarios Where codigo =+tf_codigo.getText();

int conseguiu_excluir = con_usuarios.statement.executeUpdate(sql);

if (conseguiu_excluir == 1)

{

JOptionPane.showMessageDialog(null,Exclusão realizada com sucesso);

//atualiza o ResultSet

con_usuarios.executeSQL("Select * from usuarios ");

con_usuarios.resultset.first(); //posiciona no primeiro registro

mostrar_dados();

preencher_jtable();

}

} 	

else

return;

}

catch (SQLException erro)

{

JOptionPane.showMessageDialog(null,Erro a tentar excluir o registro…”+erro);

//------FINAL DO CÓDIGO PARA EXCLUIR OS USUÁRIOS DO FORM USUARIOS---------//

}

}
private void botao_alterarActionPerformed(java.awt.event.ActionEvent evt) {

try//------INICIO DO CÓDIGO PARA ALTERAR OS DADOS DO FORM USUARIOS------------//

{

String sql = UPDATE usuarios SET nome =’”+tf_nome.getText()+"’,"+

caixa = '”+tf_caixa.getText()+"’,"+senha = '”+tf_senha.getText()+

"’ where codigo = "+tf_codigo.getText();

con_usuarios.statement.executeUpdate(sql);

JOptionPane.showMessageDialog(null, Alteração realizada com sucesso !);
// Atualiza o Resultset.
        con_usuarios.executeSQL("Select * from usuarios ");
        con_usuarios.resultset.first(); // posiciona no primeiro registro.
        preencher_jtable(); 
                  
    }
    catch (SQLException erro) 
    {
        JOptionPane.showMessageDialog(null, "Erro ao tentar alterar o registro"+erro);
//------FINAL DO CÓDIGO PARA ALTERAR OS DADOS DO FORM USUARIOS-------------//

}

}
private void tf_nomeActionPerformed(java.awt.event.ActionEvent evt) {

//------INICIO DO CÓDIGO PARA PESQUISAR OS DADOS DO FORM USUARIOS-------------//

con_usuarios.executeSQL(select * from usuarios where nome like '”+tf_nome.getText()+"%’ order by " +ordencao);

preencher_jtable();

//------FINAL DO CÓDIGO PARA PESQUISAR OS DADOS DO FORM USUARIOS--------------//

}

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

//-------INICIO DO CÓDIGO PARA PREEENCHER TEXTFIELD ATRAVÉS DA JTABLE---------//

tf_codigo.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString());

tf_nome.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 1).toString());

tf_caixa.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 2).toString());

tf_senha.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 2).toString());

//-------FINAL DO CÓDIGO PARA PREEENCHER TEXTFIELD ATRAVÉS DA JTABLE----------//

}
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {

ordem_visualizacao(codigo);

}
private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {

ordem_visualizacao(nome);

}

private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {

}

private void jTable1KeyReleased(java.awt.event.KeyEvent evt) {

//-------INICIO DO CÓDIGO PARA PREEENCHER TEXTFIELD ATRAVÉS DO TECLADO---------//

tf_codigo.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString());

tf_nome.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 1).toString());

tf_caixa.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 2).toString());

tf_senha.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 2).toString());

}

//-------FINAL DO CÓDIGO PARA PREEENCHER TEXTFIELD ATRAVÉS DO TECLADO---------//
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new cad_usuario().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton botao_alterar;
private javax.swing.JButton botao_excluir;
private javax.swing.JButton botao_gravar;
private javax.swing.JButton botao_novo;
private javax.swing.JButton botao_sair;
private javax.swing.ButtonGroup grupo_ordem;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField tf_caixa;
private javax.swing.JTextField tf_codigo;
private javax.swing.JTextField tf_nome;
private javax.swing.JPasswordField tf_senha;
// End of variables declaration
//---------------------MÉTODO PARA MOSTRAR OS DADOS---------------------------//

public void mostrar_dados()

{

try

{

tf_codigo.setText(con_usuarios.resultset.getString(codigo));

tf_nome.setText(con_usuarios.resultset.getString(nome));

tf_caixa.setText(con_usuarios.resultset.getString(caixa));

}

catch(SQLException erro)

{

JOptionPane.showMessageDialog(null,"Não localizou dados "+erro);

}

{

//-----------FINAL DO MÉTODO PARA MOSTRAR OS DADOS----------------------------//

}

//---------------------MÉTODO PARA PREENCHER O JTABLE-------------------------//

}
    public void preencher_jtable()
 {
  jTable1.getColumnModel().getColumn(0).setPreferredWidth(20);
  jTable1.getColumnModel().getColumn(1).setPreferredWidth(150);  
  jTable1.getColumnModel().getColumn(2).setPreferredWidth(20);
  DefaultTableModel modelo = (DefaultTableModel)jTable1.getModel();
  modelo.setNumRows(0);
          
         try
          {
           while (con_usuarios.resultset.next())
            modelo.addRow(new Object [] {con_usuarios.resultset.getString("Codigo"),con_usuarios.resultset.getString("nome"), con_usuarios.resultset.getString("caixa"), con_usuarios.resultset.getString("senha")});
       
         }
         catch(SQLException erro){
              JOptionPane.showMessageDialog(null, "Erro ao listar no JTable "+erro);
         }
 
  }
//---------------FINAL DO MÉTODO PARA PREENCHER O JTABLE----------------------//

public void ordem_visualizacao(String Ordem1)

{

Ordena = Ordem1;

con_usuarios.executeSQL("select * from usuarios  order by "+Ordena);

preencher_jtable();
try
    {
        con_usuarios.resultset.first();
    }
     catch (SQLException erro){
         JOptionPane.showMessageDialog(null,"Erro na ordenação dos dados "+erro);
    }
    mostrar_dados();
    
}

}

5 Respostas

Bruno_Gabriel_da_Sil

bem que vc poderia ter seguido as regras neh…
tipo vai ser meio dificil alguem ler seu codigo dessa maneira ai…
usa os padrões do forum pra posta talves tenha resultados melhores do que ele nessa forma.

vlw so um conselho pq ja aconteçeu comigo

abelgomes

pra começcar desabilitado vc faz…

seuBotao = new JButton(“Botao”);
seuBotao.setEnable(false);

e ai la no botao de salvar quando o cara clicar e salvar…

vc faz…

seuBotao.setEnable(true);

:wink:

marcosharbs

para criar um evento de mouse faça o seguinte:

nomeDoComponente.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                nomeDaFuncaoQueIraExecutar(evt);
            }
        });

exenplo de como criar a função:

private void nomeDaFuncaoQueIraExecutar(java.awt.event.MouseEvent evt) {                                  
    //aqui voce programa oq quer que aconteça qdo for clicado no componente
    //tipo se voce quiser dexa um botao desativado
    seuBotao.setEnable(false); 

}

vlw!

carloslouvato

acho que agora fica mais facil ler...

package cadastros; 

import java.awt.Dialog; 
import java.sql.SQLException; 
import javax.swing.JOptionPane; 
import classes.conexao; 
import javax.swing.*; 
import javax.swing.table.DefaultTableModel; 

/** 
* 
* @author Robson Vieira de Araújo 
*/ 
public class cad_usuario extends javax.swing.JFrame { 
conexao con_usuarios; 
private String ordencao; // Ordena no Jtable 
String ordem = "nome"; 
private String Ordena; 
/** Creates new form cad_usuario */ 
public cad_usuario() { 
initComponents(); 
setResizable(false); 
//-------CÓDIGO PARA REALIZAR CONEXAO COM A TABELA USUARIOS NO BANCO----------// 
con_usuarios = new conexao(); 
con_usuarios.conecta(); 
con_usuarios.executeSQL("select * from usuarios order by "+ordem); 
//---FINAL DO CÓDIGO PARA REALIZAR CONEXAO COM A TABELA USUARIOS NO BANCO-----// 

// ------INICIO DO CÓDIGO PARA TRAZER OS DADOS DA TABELA USUARIOS-------------// 
try 
{ 
con_usuarios.resultset.first(); 
tf_codigo.setText(con_usuarios.resultset.getString("codigo")); 
tf_nome.setText(con_usuarios.resultset.getString("nome")); 
tf_caixa.setText(con_usuarios.resultset.getString("caixa")); 
tf_senha.setText(con_usuarios.resultset.getString("senha")); 

} 
catch(SQLException erro) 

{ 
JOptionPane.showMessageDialog(null, "não localizou dados"+erro); 
} 
preencher_jtable(); // Chama método para preencher o JTable. 
} 
// -------FINAL DO CÓDIGO PARA TRAZER OS DADOS DA TABELA USUARIOS-------------// 


/** 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() { 

grupo_ordem = new javax.swing.ButtonGroup(); 
jLabel1 = new javax.swing.JLabel(); 
jLabel2 = new javax.swing.JLabel(); 
jLabel3 = new javax.swing.JLabel(); 
jLabel4 = new javax.swing.JLabel(); 
tf_codigo = new javax.swing.JTextField(); 
tf_nome = new javax.swing.JTextField(); 
tf_caixa = new javax.swing.JTextField(); 
tf_senha = new javax.swing.JPasswordField(); 
jScrollPane1 = new javax.swing.JScrollPane(); 
jTable1 = new javax.swing.JTable(); 
botao_novo = new javax.swing.JButton(); 
botao_alterar = new javax.swing.JButton(); 
botao_gravar = new javax.swing.JButton(); 
botao_excluir = new javax.swing.JButton(); 
botao_sair = new javax.swing.JButton(); 
jButton1 = new javax.swing.JButton(); 
jPanel1 = new javax.swing.JPanel(); 
jRadioButton1 = new javax.swing.JRadioButton(); 
jRadioButton2 = new javax.swing.JRadioButton(); 

setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); 
setTitle("Cadastro de Usuários/Atendentes"); 

jLabel1.setText("Código.:"); 

jLabel2.setText("Nome.:"); 

jLabel3.setText("Nº Caixa.:"); 

jLabel4.setText("Senha.:"); 

tf_codigo.addActionListener(new java.awt.event.ActionListener() { 
public void actionPerformed(java.awt.event.ActionEvent evt) { 
tf_codigoActionPerformed(evt); 
} 
}); 

tf_nome.addActionListener(new java.awt.event.ActionListener() { 
public void actionPerformed(java.awt.event.ActionEvent evt) { 
tf_nomeActionPerformed(evt); 
} 
}); 

jTable1.setModel(new javax.swing.table.DefaultTableModel( 
new Object [][] { 
{null, null, null}, 
{null, null, null}, 
{null, null, null}, 
{null, null, null}, 
{null, null, null}, 
{null, null, null}, 
{null, null, null}, 
{null, null, null}, 
{null, null, null}, 
{null, null, null}, 
{null, null, null}, 
{null, null, null}, 
{null, null, null}, 
{null, null, null}, 
{null, null, null} 
}, 
new String [] { 
"Código", "Nome", "Caixa" 
} 
) { 
boolean[] canEdit = new boolean [] { 
false, true, true 
}; 

public boolean isCellEditable(int rowIndex, int columnIndex) { 
return canEdit [columnIndex]; 
} 
}); 
jTable1.addMouseListener(new java.awt.event.MouseAdapter() { 
public void mousePressed(java.awt.event.MouseEvent evt) { 
jTable1MousePressed(evt); 
} 
}); 
jTable1.addKeyListener(new java.awt.event.KeyAdapter() { 
public void keyPressed(java.awt.event.KeyEvent evt) { 
jTable1KeyPressed(evt); 
} 
public void keyReleased(java.awt.event.KeyEvent evt) { 
jTable1KeyReleased(evt); 
} 
}); 
jScrollPane1.setViewportView(jTable1); 

botao_novo.setFont(new java.awt.Font("Arial", 0, 11)); 
botao_novo.setText("Novo"); 
botao_novo.setToolTipText("Clique aqui para criar um novo registro"); 
botao_novo.addActionListener(new java.awt.event.ActionListener() { 
public void actionPerformed(java.awt.event.ActionEvent evt) { 
botao_novoActionPerformed(evt); 
} 
}); 

botao_alterar.setFont(new java.awt.Font("Arial", 0, 11)); 
botao_alterar.setText("Alterar"); 
botao_alterar.setToolTipText("clique aqui para alterar o registro"); 
botao_alterar.addActionListener(new java.awt.event.ActionListener() { 
public void actionPerformed(java.awt.event.ActionEvent evt) { 
botao_alterarActionPerformed(evt); 
} 
}); 

botao_gravar.setFont(new java.awt.Font("Arial", 0, 11)); 
botao_gravar.setText("Gravar"); 
botao_gravar.setToolTipText("clique aqui para gravar o registro"); 
botao_gravar.addActionListener(new java.awt.event.ActionListener() { 
public void actionPerformed(java.awt.event.ActionEvent evt) { 
botao_gravarActionPerformed(evt); 
} 
}); 

botao_excluir.setFont(new java.awt.Font("Arial", 0, 11)); 
botao_excluir.setText("Excluir"); 
botao_excluir.setToolTipText("clique aqui para excluir o registro"); 
botao_excluir.addActionListener(new java.awt.event.ActionListener() { 
public void actionPerformed(java.awt.event.ActionEvent evt) { 
botao_excluirActionPerformed(evt); 
} 
}); 

botao_sair.setFont(new java.awt.Font("Arial", 0, 11)); 
botao_sair.setText("Sair"); 
botao_sair.addActionListener(new java.awt.event.ActionListener() { 
public void actionPerformed(java.awt.event.ActionEvent evt) { 
botao_sairActionPerformed(evt); 
} 
}); 

jButton1.setFont(new java.awt.Font("Arial", 0, 11)); 
jButton1.setText("Listar na Grade"); 
jButton1.setToolTipText("clique aqui para filtrar os dados na tabela"); 
jButton1.addActionListener(new java.awt.event.ActionListener() { 
public void actionPerformed(java.awt.event.ActionEvent evt) { 
jButton1ActionPerformed(evt); 
} 
}); 

jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Ordenação", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 0, 11))); // NOI18N 

grupo_ordem.add(jRadioButton1); 
jRadioButton1.setFont(new java.awt.Font("Arial", 0, 11)); 
jRadioButton1.setText("Código"); 
jRadioButton1.addActionListener(new java.awt.event.ActionListener() { 
public void actionPerformed(java.awt.event.ActionEvent evt) { 
jRadioButton1ActionPerformed(evt); 
} 
}); 

grupo_ordem.add(jRadioButton2); 
jRadioButton2.setFont(new java.awt.Font("Arial", 0, 11)); 
jRadioButton2.setSelected(true); 
jRadioButton2.setText("Nome"); 
jRadioButton2.addActionListener(new java.awt.event.ActionListener() { 
public void actionPerformed(java.awt.event.ActionEvent evt) { 
jRadioButton2ActionPerformed(evt); 
} 
}); 

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); 
jPanel1.setLayout(jPanel1Layout); 
jPanel1Layout.setHorizontalGroup( 
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
.addGroup(jPanel1Layout.createSequentialGroup() 
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
.addComponent(jRadioButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE) 
.addComponent(jRadioButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)) 
.addContainerGap(12, Short.MAX_VALUE)) 
); 
jPanel1Layout.setVerticalGroup( 
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
.addGroup(jPanel1Layout.createSequentialGroup() 
.addComponent(jRadioButton1) 
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
.addComponent(jRadioButton2) 
.addContainerGap(8, Short.MAX_VALUE)) 
); 

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
getContentPane().setLayout(layout); 
layout.setHorizontalGroup( 
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
.addGroup(layout.createSequentialGroup() 
.addContainerGap() 
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
.addGroup(layout.createSequentialGroup() 
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
.addGroup(layout.createSequentialGroup() 
.addComponent(botao_novo, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) 
.addGap(18, 18, 1 
.addComponent(botao_alterar) 
.addGap(18, 18, 1 
.addComponent(botao_gravar) 
.addGap(18, 18, 1 
.addComponent(botao_excluir, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE) 
.addGap(18, 18, 1 
.addComponent(botao_sair, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)) 
.addComponent(jButton1) 
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 422, javax.swing.GroupLayout.PREFERRED_SIZE)) 
.addContainerGap(10, Short.MAX_VALUE)) 
.addGroup(layout.createSequentialGroup() 
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
.addGroup(layout.createSequentialGroup() 
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
.addComponent(jLabel1) 
.addComponent(jLabel2)) 
.addGap(18, 18, 1 
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) 
.addComponent(tf_nome, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE) 
.addComponent(tf_codigo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))) 
.addGroup(layout.createSequentialGroup() 
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
.addComponent(jLabel3) 
.addComponent(jLabel4)) 
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
.addComponent(tf_senha, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE) 
.addComponent(tf_caixa, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))) 
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 80, Short.MAX_VALUE) 
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
.addGap(18, 18, 1))) 
); 
layout.setVerticalGroup( 
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
.addGroup(layout.createSequentialGroup() 
.addContainerGap() 
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
.addGroup(layout.createSequentialGroup() 
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
.addComponent(jLabel1) 
.addComponent(tf_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) 
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) 
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
.addComponent(jLabel2) 
.addComponent(tf_nome, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)) 
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) 
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
.addComponent(jLabel3) 
.addComponent(tf_caixa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) 
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) 
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
.addComponent(jLabel4) 
.addComponent(tf_senha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) 
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
.addComponent(jButton1)) 
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) 
.addGap(2, 2, 2) 
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE) 
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
.addComponent(botao_alterar) 
.addComponent(botao_novo) 
.addComponent(botao_gravar) 
.addComponent(botao_excluir) 
.addComponent(botao_sair)) 
.addContainerGap(15, Short.MAX_VALUE)) 
); 

java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); 
setBounds((screenSize.width-450)/2, (screenSize.height-410)/2, 450, 410); 
}// </editor-fold> 

private void tf_codigoActionPerformed(java.awt.event.ActionEvent evt) { 
// TODO add your handling code here: 
} 

private void botao_novoActionPerformed(java.awt.event.ActionEvent evt) { 
//------------INICIO DO CÓDIGO PARA GERAR NOVO REGISTRO DE USUÁRIOS-----------// 
tf_codigo.setText(""); 
tf_nome.setText(""); 
tf_caixa.setText(""); 
tf_senha.setText(""); 
tf_nome.requestFocus(); 
tf_codigo.setEditable(false); 
} 
//------------FINAL DO CÓDIGO PARA GERAR NOVO REGISTRO DE USUÁRIOS-----------// 

private void botao_sairActionPerformed(java.awt.event.ActionEvent evt) { 
dispose(); 
} 

private void botao_gravarActionPerformed(java.awt.event.ActionEvent evt) { 
//------------------INICIO DO CÓDIGO PARA GRAVAR DADOS DOS USUARIOS----------// 
try 
{ 
String sqlinsert ="insert into usuarios (nome,caixa,senha) values ('"+ 
tf_nome.getText()+"','"+ 
tf_caixa.getText()+"','"+ 
tf_senha.getText()+"')"; 
con_usuarios.statement.executeUpdate(sqlinsert); 
JOptionPane.showMessageDialog(null, "Gravação realizada com sucesso !"); 

// Atualiza o ResultSet. 
con_usuarios.executeSQL("Select * from usuarios "); 
con_usuarios.resultset.first(); // se posiciona no primeiro registro. 
mostrar_dados(); 
preencher_jtable(); 
//------------INICIO DO CÓDIGO PARA LIMPAR OS CAMPOS DO FORM USUÁRIOS---------// 
tf_codigo.setText(""); 
tf_nome.setText(""); 
tf_caixa.setText(""); 
tf_senha.setText(""); 

//------------FINAL DO CÓDIGO PARA LIMPAR OS CAMPOS DO FORM USUÁRIOS---------// 
} 
catch (SQLException erro) 
{ 
JOptionPane.showMessageDialog(null, "Erro ao tentar gravar o registro"+erro); 
} 
//------------------FINAL DO CÓDIGO PARA GRAVAR DADOS DOS USUARIOS------------// 
} 

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
con_usuarios.executeSQL("select * from usuarios where nome like '"+tf_nome.getText()+"%' order by " +ordencao); 
preencher_jtable(); 
} 

private void botao_excluirActionPerformed(java.awt.event.ActionEvent evt) { 
try//------INICIO DO CÓDIGO PARA EXCLUIR OS USUÁRIOS DO FORM USUARIOS---------// 
{ 
String sql = "select * from usuarios Where codigo = "+tf_codigo.getText(); 
con_usuarios.executeSQL(sql); 
con_usuarios.resultset.first(); 
String nome = "Deletar o Usuário: "+con_usuarios.resultset.getString("nome")+" ?"; 
int opcao_escolhida = JOptionPane.showConfirmDialog(null,nome,"Exclusão ",JOptionPane.YES_NO_OPTION); 
if (opcao_escolhida == JOptionPane.YES_OPTION) 
{ 
sql = "DELETE FROM usuarios Where codigo ="+tf_codigo.getText(); 
int conseguiu_excluir = con_usuarios.statement.executeUpdate(sql); 
if (conseguiu_excluir == 1) 
{ 
JOptionPane.showMessageDialog(null,"Exclusão realizada com sucesso"); 
//atualiza o ResultSet 
con_usuarios.executeSQL("Select * from usuarios "); 
con_usuarios.resultset.first(); //posiciona no primeiro registro 
mostrar_dados(); 
preencher_jtable(); 
} 
} 
else 
return; 
} 
catch (SQLException erro) 
{ 
JOptionPane.showMessageDialog(null,"Erro a tentar excluir o registro..."+erro); 
//------FINAL DO CÓDIGO PARA EXCLUIR OS USUÁRIOS DO FORM USUARIOS---------// 
} 
} 

private void botao_alterarActionPerformed(java.awt.event.ActionEvent evt) { 
try//------INICIO DO CÓDIGO PARA ALTERAR OS DADOS DO FORM USUARIOS------------// 
{ 
String sql = "UPDATE usuarios SET nome ='"+tf_nome.getText()+"',"+ 
"caixa = '"+tf_caixa.getText()+"',"+"senha = '"+tf_senha.getText()+ 
"' where codigo = "+tf_codigo.getText(); 
con_usuarios.statement.executeUpdate(sql); 
JOptionPane.showMessageDialog(null, "Alteração realizada com sucesso !"); 

// Atualiza o Resultset. 
con_usuarios.executeSQL("Select * from usuarios "); 
con_usuarios.resultset.first(); // posiciona no primeiro registro. 
preencher_jtable(); 

} 
catch (SQLException erro) 
{ 
JOptionPane.showMessageDialog(null, "Erro ao tentar alterar o registro"+erro); 
//------FINAL DO CÓDIGO PARA ALTERAR OS DADOS DO FORM USUARIOS-------------// 
} 
} 

private void tf_nomeActionPerformed(java.awt.event.ActionEvent evt) { 
//------INICIO DO CÓDIGO PARA PESQUISAR OS DADOS DO FORM USUARIOS-------------// 
con_usuarios.executeSQL("select * from usuarios where nome like '"+tf_nome.getText()+"%' order by " +ordencao); 
preencher_jtable(); 
//------FINAL DO CÓDIGO PARA PESQUISAR OS DADOS DO FORM USUARIOS--------------// 
} 
private void jTable1MousePressed(java.awt.event.MouseEvent evt) { 
//-------INICIO DO CÓDIGO PARA PREEENCHER TEXTFIELD ATRAVÉS DA JTABLE---------// 
tf_codigo.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString()); 
tf_nome.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 1).toString()); 
tf_caixa.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 2).toString()); 
tf_senha.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 2).toString()); 
//-------FINAL DO CÓDIGO PARA PREEENCHER TEXTFIELD ATRAVÉS DA JTABLE----------// 
} 

private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
ordem_visualizacao("codigo"); 
} 

private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) { 
ordem_visualizacao("nome"); 
} 

private void jTable1KeyPressed(java.awt.event.KeyEvent evt) { 

} 

private void jTable1KeyReleased(java.awt.event.KeyEvent evt) { 
//-------INICIO DO CÓDIGO PARA PREEENCHER TEXTFIELD ATRAVÉS DO TECLADO---------// 
tf_codigo.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString()); 
tf_nome.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 1).toString()); 
tf_caixa.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 2).toString()); 
tf_senha.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 2).toString()); 
} 
//-------FINAL DO CÓDIGO PARA PREEENCHER TEXTFIELD ATRAVÉS DO TECLADO---------// 

/** 
* @param args the command line arguments 
*/ 
public static void main(String args[]) { 
java.awt.EventQueue.invokeLater(new Runnable() { 
public void run() { 
new cad_usuario().setVisible(true); 
} 
}); 
} 

// Variables declaration - do not modify 
private javax.swing.JButton botao_alterar; 
private javax.swing.JButton botao_excluir; 
private javax.swing.JButton botao_gravar; 
private javax.swing.JButton botao_novo; 
private javax.swing.JButton botao_sair; 
private javax.swing.ButtonGroup grupo_ordem; 
private javax.swing.JButton jButton1; 
private javax.swing.JLabel jLabel1; 
private javax.swing.JLabel jLabel2; 
private javax.swing.JLabel jLabel3; 
private javax.swing.JLabel jLabel4; 
private javax.swing.JPanel jPanel1; 
private javax.swing.JRadioButton jRadioButton1; 
private javax.swing.JRadioButton jRadioButton2; 
private javax.swing.JScrollPane jScrollPane1; 
private javax.swing.JTable jTable1; 
private javax.swing.JTextField tf_caixa; 
private javax.swing.JTextField tf_codigo; 
private javax.swing.JTextField tf_nome; 
private javax.swing.JPasswordField tf_senha; 
// End of variables declaration 

//---------------------MÉTODO PARA MOSTRAR OS DADOS---------------------------// 
public void mostrar_dados() 
{ 
try 
{ 
tf_codigo.setText(con_usuarios.resultset.getString("codigo")); 
tf_nome.setText(con_usuarios.resultset.getString("nome")); 
tf_caixa.setText(con_usuarios.resultset.getString("caixa")); 
} 
catch(SQLException erro) 
{ 
JOptionPane.showMessageDialog(null,"Não localizou dados "+erro); 
} 
{ 
//-----------FINAL DO MÉTODO PARA MOSTRAR OS DADOS----------------------------// 
} 


//---------------------MÉTODO PARA PREENCHER O JTABLE-------------------------// 

} 
public void preencher_jtable() 
{ 
jTable1.getColumnModel().getColumn(0).setPreferredWidth(20); 
jTable1.getColumnModel().getColumn(1).setPreferredWidth(150); 
jTable1.getColumnModel().getColumn(2).setPreferredWidth(20); 
DefaultTableModel modelo = (DefaultTableModel)jTable1.getModel(); 
modelo.setNumRows(0); 

try 
{ 
while (con_usuarios.resultset.next()) 
modelo.addRow(new Object [] {con_usuarios.resultset.getString("Codigo"),con_usuarios.resultset.getString("nome"), con_usuarios.resultset.getString("caixa"), con_usuarios.resultset.getString("senha")}); 

} 
catch(SQLException erro){ 
JOptionPane.showMessageDialog(null, "Erro ao listar no JTable "+erro); 
} 

} 
//---------------FINAL DO MÉTODO PARA PREENCHER O JTABLE----------------------// 
public void ordem_visualizacao(String Ordem1) 
{ 
Ordena = Ordem1; 
con_usuarios.executeSQL("select * from usuarios order by "+Ordena); 
preencher_jtable(); 

try 
{ 
con_usuarios.resultset.first(); 
} 
catch (SQLException erro){ 
JOptionPane.showMessageDialog(null,"Erro na ordenação dos dados "+erro); 
} 
mostrar_dados(); 

} 


}

não esqueça de colocar entre code... caso tenha duvida tem um tópico no forum que explica como fazer.
valewwww .

abraço

R

Agradeço a todos pela paciência com que demonstraram para me ajudar, desculpem as minhas mancadas, pois estou iniciando no java e este é o meu primeiro post…

Valeu…

Criado 28 de outubro de 2008
Ultima resposta 29 de out. de 2008
Respostas 5
Participantes 5