Olá, estou fazendo um projeto Java para cadastro de Motorista com JPanel. Porém aconteceu um erro que não sei resolver no botão salvar. Quando chamo o GetText ele apresenta esse erro “String Cannot be Converted to Motorista”. Nesta tela:
package my.contacteditor;
import Conexao.ConnectionFactory;
import DAO.MotoristaDAO;
public class CadastroMotorista extends javax.swing.JFrame {
ConnectionFactory conecta = new ConnectionFactory();
MotoristaDAO motoristaDAO = new MotoristaDAO();
Motorista motorista = new Motorista();
public CadastroMotorista() {
initComponents();
this.setLocationRelativeTo(null);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
txtId = new javax.swing.JTextField();
txtNome = new javax.swing.JTextField();
btnSalvar = new javax.swing.JButton();
btnCancelar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Cadastro Motorista");
jLabel2.setText("Id:");
jLabel3.setText("Nome:");
txtNome.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
txtNome.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtNomeActionPerformed(evt);
}
});
btnSalvar.setText("Salvar");
btnSalvar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSalvarActionPerformed(evt);
}
});
btnCancelar.setText("Cancelar");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(btnSalvar)
.addGap(38, 38, 38)
.addComponent(btnCancelar)))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(21, 21, 21)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnSalvar)
.addComponent(btnCancelar))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, 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()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {
//Trecho do erro: String cannot be converted to Motorista
MotoristaDAO.save(txtNome.getText());
}
private void txtNomeActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void txtNomeActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* @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(CadastroMotorista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CadastroMotorista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CadastroMotorista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CadastroMotorista.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 CadastroMotorista().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnCancelar;
private javax.swing.JButton btnSalvar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField txtId;
private javax.swing.JTextField txtNome;
// End of variables declaration
}
--------------------------------------------------------------------------------------------------
Classe DAO
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import Conexao.ConnectionFactory;
import Model.Motorista;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Alfa Informática
*/
public class MotoristaDAO {
private Connection con = null;
public MotoristaDAO() {
con = ConnectionFactory.getConnection();
}
public boolean save(Motorista motorista){
String sql = "INSERT INTO motoristas (nome) VALUES (?)";
PreparedStatement stmt = null;
try {
stmt = con.prepareStatement(sql);
stmt.setString(1, motorista.getNome());
stmt.executeUpdate();
return true;
} catch (SQLException ex) {
System.out.println("Erro"+ex);
return false;
}
finally{
ConnectionFactory.closeConection(con, stmt);
}
}
public boolean update(Motorista motorista){
String sql = "UPDATE motoristas SET nome = ? WHERE idMotoristas = ?";
PreparedStatement stmt = null;
try {
stmt = con.prepareStatement(sql);
stmt.setString(1, motorista.getNome());
stmt.setInt(2, motorista.getId());
stmt.executeUpdate();
return true;
} catch (SQLException ex) {
System.out.println("Erro"+ex);
return false;
}
finally{
ConnectionFactory.closeConection(con, stmt);
}
}
public boolean delete(Motorista motorista){
String sql = "DELETE FROM motoristas WHERE idMotoristas = ?";
PreparedStatement stmt = null;
try {
stmt = con.prepareStatement(sql);
stmt.setInt(1, motorista.getId());
stmt.executeUpdate();
return true;
} catch (SQLException ex) {
System.out.println("Erro"+ex);
return false;
}
finally{
ConnectionFactory.closeConection(con, stmt);
}
}
public List <Motorista> findAll(){
String sql = "SELECT * FROM motoristas";
PreparedStatement stmt = null;
ResultSet rs = null;
List<Motorista> motoristas = new ArrayList<>();
try {
stmt = con.prepareStatement(sql);
rs = stmt.executeQuery();
while(rs.next()){
Motorista motorista = new Motorista();
motorista.setNome(rs.getString("Nome"));
motoristas.add(motorista);
}
} catch (SQLException ex) {
System.out.println("Erro"+ex);
}finally{
ConnectionFactory.closeConection(con, stmt, rs);
}
return motoristas;
}
}
---------------------------------------------------------------------------------------------
Classe Motorista
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Model;
/**
*
* @author Alfa Informática
*/
public class Motorista {
private int id;
private String nome;
public Motorista() {
}
public Motorista(String nome) {
this.nome = nome;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}