Galera criei um projeto e ele fica carregando mas não mostra a GUI para iniciar. Será que tem algum erro? Preciso de ajuda!
ivProjeto.zip (40,5,KB)
edit: A conexao tinha diversos erros, nem eram ortográficos mas enfim, um programador me ajudou.
Galera criei um projeto e ele fica carregando mas não mostra a GUI para iniciar. Será que tem algum erro? Preciso de ajuda!
ivProjeto.zip (40,5,KB)
edit: A conexao tinha diversos erros, nem eram ortográficos mas enfim, um programador me ajudou.
mostra a classe main
package gui;
import DAO.UsuarioDAO;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import modelo.ModelTable;
import modelo.Usuario;
public class UsuarioGUI extends javax.swing.JFrame {
private Usuario objUsuario;
private UsuarioDAO objDAO;
private boolean buscar = false;
public UsuarioGUI() {
initComponents();
//Centralizando a janela
this.setLocationRelativeTo(null);
// Impede que a janela seja redimencionada
this.setResizable(false);
// Trocando cursor para HAND CURSOR(Maozinha)
// jButtonRefresh.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
// Variavel con recebendo a conexao
carregarTable(null);
}
// Metodo que realiza conexao com o banco, faz uma instrucao Query(select)
// para jogar na JTable atraves do modelo de tabela (ModelTabel.java)
public void carregarTable(Usuario objUsuario) {
objDAO = new UsuarioDAO();
ArrayList dados = new ArrayList();
if (buscar) {
dados = objDAO.buscar(objUsuario);
} else {
objUsuario = new Usuario();
dados = objDAO.listarTodos();
}
String[] colunas = objUsuario.getColunas();
ModelTable modelo = new ModelTable(dados, colunas);
tbListagemUsuario.setModel(modelo);
tbListagemUsuario.getColumnModel().getColumn(0).setPreferredWidth(80);
tbListagemUsuario.getColumnModel().getColumn(0).setResizable(false);
tbListagemUsuario.getColumnModel().getColumn(1).setPreferredWidth(120);
tbListagemUsuario.getColumnModel().getColumn(1).setResizable(false);
tbListagemUsuario.getColumnModel().getColumn(2).setPreferredWidth(250);
tbListagemUsuario.getColumnModel().getColumn(2).setResizable(false);
tbListagemUsuario.getTableHeader().setReorderingAllowed(false);
// tbListagemUsuario.setAutoResizeMode(tbListagemUsuario.AUTO_RESIZE_ALL_COLUMNS);
// tbListagemUsuario.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
// Metodo responsavel por selecionar um registro ao clicar ou seguir com as setas do teclado
// na JTable, e realizar a vinculacao do mesmo nos TextFields
public void selectRegistryTable() {
txtID.setText(tbListagemUsuario.getValueAt(tbListagemUsuario.getSelectedRow(), 0).toString());
//Object objNome = tbListagemUsuario.getValueAt(tbListagemUsuario.getSelectedRow(), 1);
txtNome.setText(tbListagemUsuario.getValueAt(tbListagemUsuario.getSelectedRow(), 1).toString());
txtDt_nasc.setText(tbListagemUsuario.getValueAt(tbListagemUsuario.getSelectedRow(), 2).toString());
txtEmail.setText(tbListagemUsuario.getValueAt(tbListagemUsuario.getSelectedRow(), 3).toString());
}
/**
* 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();
jLabel2 = new javax.swing.JLabel();
txtNome = new javax.swing.JTextField();
txtDt_nasc = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtEmail = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
tbnLimpar = new javax.swing.JButton();
tbnSalvar = new javax.swing.JButton();
tbnExit = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tbListagemUsuario = new javax.swing.JTable();
txtID = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
btnDeletar = new javax.swing.JButton();
btnBuscar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel1.setText("CADASTRO DE USUÁRIOS");
jLabel2.setText("Nome");
txtNome.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtNomeActionPerformed(evt);
}
});
txtDt_nasc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtDt_nascActionPerformed(evt);
}
});
jLabel3.setText("Data de Nascimento");
jLabel5.setText("Email");
tbnLimpar.setText("Limpar");
tbnLimpar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tbnLimparActionPerformed(evt);
}
});
tbnSalvar.setText("Salvar");
tbnSalvar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tbnSalvarActionPerformed(evt);
}
});
tbnExit.setText("Sair");
tbnExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tbnExitActionPerformed(evt);
}
});
tbListagemUsuario.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}
},
new String [] {
"ID", "Nome", "CPF", "Email", "Telefone"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, true, true, true, true
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tbListagemUsuario.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tbListagemUsuarioMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tbListagemUsuario);
txtID.setEditable(false);
jLabel6.setText("ID");
btnDeletar.setText("Deletar");
btnDeletar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDeletarActionPerformed(evt);
}
});
btnBuscar.setText("Buscar");
btnBuscar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBuscarActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel5)
.addComponent(txtNome)
.addComponent(txtDt_nasc, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtEmail))
.addGroup(layout.createSequentialGroup()
.addComponent(tbnSalvar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tbnLimpar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnDeletar)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnBuscar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tbnExit)))
.addGap(86, 86, 86))))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel6)
.addGap(16, 16, 16)
.addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtDt_nasc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(52, 52, 52)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(tbnLimpar)
.addComponent(tbnSalvar)
.addComponent(tbnExit)
.addComponent(btnDeletar)
.addComponent(btnBuscar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void txtNomeActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void txtDt_nascActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void tbnSalvarActionPerformed(java.awt.event.ActionEvent evt) {
objUsuario = new Usuario();
objUsuario.setId(txtID.getText());
objUsuario.setNome(txtNome.getText());
objUsuario.setDt_nasc(txtDt_nasc.getText());
objUsuario.setEmail(txtEmail.getText());
// fazendo a valida��o dos dados
if ((txtNome.getText().isEmpty()) || (txtDt_nasc.getText().isEmpty()) || (txtEmail.getText().isEmpty())){
JOptionPane.showMessageDialog(null, "Informe valores para os campos");
} else {
// instanciando a classe UsuarioDAO do pacote dao e criando seu objeto dao
objDAO = new UsuarioDAO();
objDAO.salvar(objUsuario);
JOptionPane.showMessageDialog(null, "Usuario " + txtNome.getText() + " inserido com sucesso! ");
}
carregarTable(null);
// apaga os dados preenchidos nos campos de texto
setClear();
}
private void tbnLimparActionPerformed(java.awt.event.ActionEvent evt) {
setClear();
carregarTable(null);
}
private void tbnExitActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void tbListagemUsuarioMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
selectRegistryTable();
}
private void btnDeletarActionPerformed(java.awt.event.ActionEvent evt) {
objUsuario.setId(txtID.getText());
// fazendo a valida��o dos dados
if ((txtID.getText().isEmpty())) {
JOptionPane.showMessageDialog(null, "Informe valores para os campos");
} else {
// instanciando a classe UsuarioDAO do pacote dao e criando seu objeto dao
objDAO = new UsuarioDAO();
objDAO.deletar(objUsuario);
JOptionPane.showMessageDialog(null, "Usuario Removido com Sucesso! ");
}
carregarTable(null);
// apaga os dados preenchidos nos campos de texto
setClear();
}
private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {
objUsuario = new Usuario();
objUsuario.setNome(txtNome.getText());
objUsuario.setDt_nasc(txtDt_nasc.getText());
// fazendo a valida��o dos dados
if ((!txtNome.getText().isEmpty()) || (!txtDt_nasc.getText().isEmpty())) {
// instanciando a classe UsuarioDAO do pacote dao e criando seu objeto dao
objDAO = new UsuarioDAO();
buscar = true;
carregarTable(objUsuario);
}else{
buscar = false;
carregarTable(null);
}
// apaga os dados preenchidos nos campos de texto
setClear();
}
public void setClear() {
txtID.setText(null);
txtNome.setText(null);
txtDt_nasc.setText(null);
txtEmail.setText(null);
}
/**
* @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(UsuarioGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(UsuarioGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(UsuarioGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(UsuarioGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new UsuarioGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnBuscar;
private javax.swing.JButton btnDeletar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tbListagemUsuario;
private javax.swing.JButton tbnExit;
private javax.swing.JButton tbnLimpar;
private javax.swing.JButton tbnSalvar;
private javax.swing.JTextField txtDt_nasc;
private javax.swing.JTextField txtEmail;
private javax.swing.JTextField txtID;
private javax.swing.JTextField txtNome;
// End of variables declaration
}
Aparentemente ta normal. Dá algum erro?
Não da erro mas a saída não passa disto:
cd C:\Users\aless\Documents\NetBeansProjects\ivProjeto; "JAVA_HOME=C:\\Program Files\\Java\\jdk1.8.0_111" M2_HOME=C:\\Users\\aless\\Downloads\\apache-maven-3.6.3 cmd /c "\"\"C:\\Users\\aless\\Downloads\\apache-maven-3.6.3\\bin\\mvn.cmd\" -Dexec.args=\"-classpath %classpath gui.UsuarioGUI\" -Dexec.executable=\"C:\\Program Files\\Java\\jdk1.8.0_111\\bin\\java.exe\" -Dmaven.ext.class.path=\"C:\\Program Files\\NetBeans 8.2\\java\\maven-nblib\\netbeans-eventspy.jar\" -Dfile.encoding=UTF-8 --check-plugin-updates org.codehaus.mojo:exec-maven-plugin:1.2.1:exec\""
Running NetBeans Compile On Save execution. Phase execution is skipped and output directories of dependency projects (with Compile on Save turned on) will be used instead of their jar artifacts.
Command line option -cpu is deprecated and will be removed in future Maven versions.
Scanning for projects...
----------------------< com.mycompany:IVprojeto >-----------------------
Building IVprojeto 1.0-SNAPSHOT
--------------------------------[ jar ]---------------------------------
--- exec-maven-plugin:1.2.1:exec (default-cli) @ IVprojeto ---
java.lang.NullPointerException
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: conexao==null
at apoio.ConexaoBD.getConnection(ConexaoBD.java:49)
at DAO.UsuarioDAO.<init>(UsuarioDAO.java:19)
at gui.UsuarioGUI.carregarTable(UsuarioGUI.java:36)
at gui.UsuarioGUI.<init>(UsuarioGUI.java:29)
at gui.UsuarioGUI$10.run(UsuarioGUI.java:395)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
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:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
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)
Ué, mas deu erro:
Sua conexão está nula.
Não estou conseguindo arrumar
Acho que não consigo conectar por usar netbeans 8.2 para postgresql 12, no IDE aparece apenas o driver 9.4…
Não vi que vc tinha respondido. Não é isso, a sua instância de conexão está nula.
Mostra a a classe de conexão aqui
Olha fiz umas modificações e instalei o mysql.
da esses erros:
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/ProjIV
at factory.ConnectionFactory.getConnection(ConnectionFactory.java:18)
at dao.UsuarioDAO.<init>(UsuarioDAO.java:25)
at gui.UsuarioGUI.carregarTable(UsuarioGUI.java:46)
at gui.UsuarioGUI.<init>(UsuarioGUI.java:39)
at gui.UsuarioGUI$11.run(UsuarioGUI.java:443)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
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:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
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)
Caused by: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/ProjIV
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at factory.ConnectionFactory.getConnection(ConnectionFactory.java:16)
... 18 more
CONSTRUÇÃO PARADA (tempo total: 19 minutos 55 segundos)
Meu GUI:
package gui;
import dao.UsuarioDAO;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import modelo.ModelTable;
import modelo.Usuario;
public class UsuarioGUI extends javax.swing.JFrame {
private Usuario objUsuario;
private UsuarioDAO objDAO;
private boolean buscar = false;
/**
* Creates new form UsuarioGUI
*/
public UsuarioGUI() {
initComponents();
//Centralizando a janela
this.setLocationRelativeTo(null);
// Impede que a janela seja redimencionada
this.setResizable(false);
// Trocando cursor para HAND CURSOR(Maozinha)
// jButtonRefresh.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
// Variavel con recebendo a conexao
carregarTable(null);
}
// Metodo que realiza conexao com o banco, faz uma instrucao Query(select)
// para jogar na JTable atraves do modelo de tabela (ModelTabel.java)
public void carregarTable(Usuario objUsuario) {
objDAO = new UsuarioDAO();
ArrayList dados = new ArrayList();
if (buscar) {
dados = objDAO.buscar(objUsuario);
} else {
objUsuario = new Usuario();
dados = objDAO.listarTodos();
}
String[] colunas = objUsuario.getColunas();
ModelTable modelo = new ModelTable(dados, colunas);
tbListagemUsuario.setModel(modelo);
tbListagemUsuario.getColumnModel().getColumn(0).setPreferredWidth(80);
tbListagemUsuario.getColumnModel().getColumn(0).setResizable(false);
tbListagemUsuario.getColumnModel().getColumn(1).setPreferredWidth(120);
tbListagemUsuario.getColumnModel().getColumn(1).setResizable(false);
tbListagemUsuario.getColumnModel().getColumn(2).setPreferredWidth(250);
tbListagemUsuario.getColumnModel().getColumn(2).setResizable(false);
tbListagemUsuario.getTableHeader().setReorderingAllowed(false);
// tbListagemUsuario.setAutoResizeMode(tbListagemUsuario.AUTO_RESIZE_ALL_COLUMNS);
// tbListagemUsuario.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
// Metodo responsavel por selecionar um registro ao clicar ou seguir com as setas do teclado
// na JTable, e realizar a vinculacao do mesmo nos TextFields
public void selectRegistryTable() {
txtID.setText(tbListagemUsuario.getValueAt(tbListagemUsuario.getSelectedRow(), 0).toString());
//Object objNome = tbListagemUsuario.getValueAt(tbListagemUsuario.getSelectedRow(), 1);
txtNome.setText(tbListagemUsuario.getValueAt(tbListagemUsuario.getSelectedRow(), 1).toString());
txtCPF.setText(tbListagemUsuario.getValueAt(tbListagemUsuario.getSelectedRow(), 2).toString());
txtEmail.setText(tbListagemUsuario.getValueAt(tbListagemUsuario.getSelectedRow(), 3).toString());
txtTelefone.setText(tbListagemUsuario.getValueAt(tbListagemUsuario.getSelectedRow(), 4).toString());
}
/**
* 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();
jLabel2 = new javax.swing.JLabel();
txtNome = new javax.swing.JTextField();
txtCPF = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtTelefone = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
txtEmail = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
tbnLimpar = new javax.swing.JButton();
tbnSalvar = new javax.swing.JButton();
tbnExit = new javax.swing.JButton();
tbnExit1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tbListagemUsuario = new javax.swing.JTable();
txtID = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
btnDeletar = new javax.swing.JButton();
jLabel7 = new javax.swing.JLabel();
btnBuscar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel1.setText("CADASTRO DE USUÁRIOS");
jLabel2.setText("Nome");
txtNome.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtNomeActionPerformed(evt);
}
});
txtCPF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtCPFActionPerformed(evt);
}
});
jLabel3.setText("CPF");
jLabel4.setText("Telefone");
jLabel5.setText("Email");
tbnLimpar.setText("Limpar");
tbnLimpar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tbnLimparActionPerformed(evt);
}
});
tbnSalvar.setText("Salvar");
tbnSalvar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tbnSalvarActionPerformed(evt);
}
});
tbnExit.setText("Sair");
tbnExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tbnExitActionPerformed(evt);
}
});
tbnExit1.setText("Testar Conexão");
tbnExit1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tbnExit1ActionPerformed(evt);
}
});
tbListagemUsuario.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}
},
new String [] {
"ID", "Nome", "CPF", "Email", "Telefone"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, true, true, true, true
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tbListagemUsuario.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tbListagemUsuarioMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tbListagemUsuario);
txtID.setEditable(false);
jLabel6.setText("ID");
btnDeletar.setText("Deletar");
btnDeletar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDeletarActionPerformed(evt);
}
});
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel7.setText("Com MySQL");
btnBuscar.setText("Buscar");
btnBuscar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBuscarActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel7))
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5)
.addComponent(txtNome)
.addComponent(txtCPF, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtEmail)
.addComponent(txtTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(tbnSalvar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tbnLimpar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnDeletar)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tbnExit1, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(btnBuscar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tbnExit)))))
.addGap(86, 86, 86))))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(jLabel7))
.addGap(8, 8, 8)
.addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tbnExit1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtCPF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(tbnLimpar)
.addComponent(tbnSalvar)
.addComponent(tbnExit)
.addComponent(btnDeletar)
.addComponent(btnBuscar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void txtNomeActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void txtCPFActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void tbnSalvarActionPerformed(java.awt.event.ActionEvent evt) {
objUsuario = new Usuario();
objUsuario.setId(txtID.getText());
objUsuario.setNome(txtNome.getText());
objUsuario.setCpf(txtCPF.getText());
objUsuario.setEmail(txtEmail.getText());
objUsuario.setTelefone(txtTelefone.getText());
// fazendo a validação dos dados
if ((txtNome.getText().isEmpty()) || (txtCPF.getText().isEmpty()) || (txtEmail.getText().isEmpty()) || (txtTelefone.getText().isEmpty())) {
JOptionPane.showMessageDialog(null, "Informe valores para os campos");
} else {
// instanciando a classe UsuarioDAO do pacote dao e criando seu objeto dao
objDAO = new UsuarioDAO();
objDAO.salvar(objUsuario);
JOptionPane.showMessageDialog(null, "Usuário " + txtNome.getText() + " inserido com sucesso! ");
}
carregarTable(null);
// apaga os dados preenchidos nos campos de texto
setClear();
}
private void tbnLimparActionPerformed(java.awt.event.ActionEvent evt) {
setClear();
carregarTable(null);
}
private void tbnExitActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void tbnExit1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
UsuarioDAO.testarConexao();
} catch (SQLException ex) {
ex.getMessage();
}
}
private void tbListagemUsuarioMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
selectRegistryTable();
}
private void btnDeletarActionPerformed(java.awt.event.ActionEvent evt) {
objUsuario.setId(txtID.getText());
// fazendo a validação dos dados
if ((txtID.getText().isEmpty())) {
JOptionPane.showMessageDialog(null, "Informe valores para os campos");
} else {
// instanciando a classe UsuarioDAO do pacote dao e criando seu objeto dao
objDAO = new UsuarioDAO();
objDAO.deletar(objUsuario);
JOptionPane.showMessageDialog(null, "Usuário Removido com Sucesso! ");
}
carregarTable(null);
// apaga os dados preenchidos nos campos de texto
setClear();
}
private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {
objUsuario = new Usuario();
objUsuario.setNome(txtNome.getText());
objUsuario.setCpf(txtCPF.getText());
// fazendo a validação dos dados
if ((!txtNome.getText().isEmpty()) || (!txtCPF.getText().isEmpty())) {
// instanciando a classe UsuarioDAO do pacote dao e criando seu objeto dao
objDAO = new UsuarioDAO();
buscar = true;
carregarTable(objUsuario);
}else{
buscar = false;
carregarTable(null);
}
// apaga os dados preenchidos nos campos de texto
setClear();
}
public void setClear() {
txtID.setText(null);
txtNome.setText(null);
txtCPF.setText(null);
txtEmail.setText(null);
txtTelefone.setText(null);
}
/**
* @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(UsuarioGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(UsuarioGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(UsuarioGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(UsuarioGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new UsuarioGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnBuscar;
private javax.swing.JButton btnDeletar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tbListagemUsuario;
private javax.swing.JButton tbnExit;
private javax.swing.JButton tbnExit1;
private javax.swing.JButton tbnLimpar;
private javax.swing.JButton tbnSalvar;
private javax.swing.JTextField txtCPF;
private javax.swing.JTextField txtEmail;
private javax.swing.JTextField txtID;
private javax.swing.JTextField txtNome;
private javax.swing.JTextField txtTelefone;
// End of variables declaration
}
DAO:
package DAO;
import apoio.ConexaoBD;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import java.sql.*;
import java.util.*;
public class UsuarioDAO {
private Connection connection;
Long id;
String nome;
String dt_nasc;
String email;
public UsuarioDAO() {
this.connection = new ConexaoBD().getCon();
}
public void salvar(modelo.Usuario objUsuario) {
try {
String sql;
if (String.valueOf(objUsuario.getId()).isEmpty()) {
sql = "INSERT INTO usuario(nome,dt_nasc,email) VALUES(?,?,?)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, objUsuario.getNome());
stmt.setString(2, objUsuario.getDt_nasc());
stmt.setString(3, objUsuario.getEmail());
stmt.execute();
stmt.close();
} else {
sql = "UPDATE usuario SET nome = ?, cpf = ?, email = ?, telefone = ? WHERE usuario.id = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(5, objUsuario.getId());
stmt.setString(1, objUsuario.getNome());
stmt.setString(2, objUsuario.getDt_nasc());
stmt.setString(3, objUsuario.getEmail());
stmt.execute();
stmt.close();
}
} catch (SQLException u) {
throw new RuntimeException(u);
}
}
public ArrayList buscar(modelo.Usuario objUsuario) {
try {
String sql = "";
if (!objUsuario.getNome().isEmpty()) {
sql = "SELECT * FROM usuario WHERE nome LIKE '%" + objUsuario.getNome() + "%' ";
} else if (!objUsuario.getDt_nasc().isEmpty()) {
sql = "SELECT * FROM usuario WHERE cpf LIKE '%" + objUsuario.getDt_nasc() + "%' ";
}
ArrayList dado = new ArrayList();
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
dado.add(new Object[]{
rs.getInt("id"),
rs.getString("nome"),
rs.getString("dt_nasc"),
rs.getString("email"),
});
}
ps.close();
rs.close();
connection.close();
return dado;
} catch (SQLException e) {
e.getMessage();
JOptionPane.showMessageDialog(null, "Erro preencher o ArrayList");
return null;
}
}
public void deletar(modelo.Usuario objUsuario) {
try {
String sql;
if (!String.valueOf(objUsuario.getId()).isEmpty()) {
sql = "DELETE FROM usuario WHERE usuario.id = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, objUsuario.getId());
stmt.execute();
stmt.close();
}
} catch (SQLException u) {
throw new RuntimeException(u);
}
}
public ArrayList listarTodos() {
try {
ArrayList dado = new ArrayList();
PreparedStatement ps = connection.prepareStatement("SELECT * FROM usuario");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
dado.add(new Object[]{
rs.getInt("id"),
rs.getString("nome"),
rs.getString("dt_nasc"),
rs.getString("email"),
});
}
ps.close();
rs.close();
connection.close();
return dado;
} catch (SQLException e) {
e.getMessage();
JOptionPane.showMessageDialog(null, "Erro preencher o ArrayList");
return null;
}
}
public static void testarConexao() throws SQLException {
try (Connection objConnection = new ConexaoBD().getCon()) {
JOptionPane.showMessageDialog(null, "Conexão realizada com sucesso! ");
}
}
}
Connection:
// situa em qual package ou ?pacote? está a classe
package factory;
// faz as importações de classes necessárias para o funcionamento do programa
import java.sql.Connection;
// conexão SQL para Java
import java.sql.DriverManager;
// driver de conexão SQL para Java
import java.sql.SQLException;
// classe para tratamento de exceções
public class ConnectionFactory {
public Connection getConnection() {
try {
return DriverManager.getConnection("jdbc:mysql://localhost/ProjIV", "root", "mysql");
} catch (SQLException excecao) {
throw new RuntimeException(excecao);
}
}
}
Vc precisa incluir a biblioteca do MySQL no projeto
Não é ir em bibliotecas / Adicionar biblioteca?
Isso mesmo