Hola estoy haciendo una aplicación de escritorio con java y base de datos mysql
pero cuando compilo el try y catch me captura un error que es java.lang.NullPointerException
y no se llena el jtable pero sí guarda los datos que inserto en los textbox y en los combos antes de que ponga el try catch me marcaba error en la siguiente línea.
fila.addElement(cliente.getNacionalidad().getNombre());
el codigo de la clase Nacionalidad:
package entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="tb_nacionalidad")
public class Nacionalidad implements Serializable {
@Id
@Column(name="nac_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column(name="nac_nom")
private String nombre;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
el codigo de la clase cliente:
package entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="tb_cliente")
public class Cliente implements Serializable{
@Id
@Column(name="cli_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column(name="cli_nom")
private String nombre;
@Column(name="prof_ape")
private String apellido;
@Column(name="prof_tel")
private String telefono;
@ManyToOne
@JoinColumn(name="dis_id")
private Distrito distrito;
@ManyToOne
@JoinColumn(name="nac_id")
private Nacionalidad nacionalidad;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public Distrito getDistrito() {
return distrito;
}
public void setDistrito(Distrito distrito) {
this.distrito = distrito;
}
public Nacionalidad getNacionalidad() {
return nacionalidad;
}
public void setNacionalidad(Nacionalidad nacionalidad) {
this.nacionalidad = nacionalidad;
}
}
mi código completo es:
public class UICliente extends javax.swing.JFrame {
private List<Nacionalidad> listaNacionalidad;
private List<Distrito> listaDistrito;
private List<Cliente> listaCliente;
private DefaultTableModel modelCliente;
public UICliente() {
initComponents();
cargarNacionalidades();
cargarDistritos();
cargarClientes();
}
private void cargarClientes(){
try{
modelCliente = (DefaultTableModel)this.tblCliente.getModel();
ClienteService clienteService = ServiceLocate.getClienteService();
listaCliente = clienteService.listarTodo();
modelCliente.getDataVector().removeAllElements();
for(Cliente cliente:listaCliente){
Vector fila = new Vector();
fila.addElement(cliente.getId());
fila.addElement(cliente.getNombre());
fila.addElement(cliente.getApellido());
fila.addElement(cliente.getTelefono());
fila.addElement(cliente.getNacionalidad().getNombre());//Navegabilidad
fila.addElement(cliente.getDistrito().getNombre()); //Navegabilidad
modelCliente.addRow(fila);
}}catch(Exception excepcion){
System.out.println("El objeto error es de tipo " + excepcion);
}
}
private void cargarDistritos(){
DistritoService distritoService = ServiceLocate.getDistritoService();
listaDistrito = distritoService.listarTodos();
for(Distrito distrito:listaDistrito){
this.cboDistrito.addItem(distrito.getNombre());
}
}
private void cargarNacionalidades(){
NacionalidadService nacionalidadService = ServiceLocate.getNacionalidadService();
listaNacionalidad = nacionalidadService.listarTodos();
for(Nacionalidad nacionalidad:listaNacionalidad){
this.cboNacionalidad.addItem(nacionalidad.getNombre());
}
}
/**
* 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();
txtNombre = new javax.swing.JTextField();
cboDistrito = new javax.swing.JComboBox<>();
jScrollPane1 = new javax.swing.JScrollPane();
tblCliente = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
txtApellido = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
txtTelefono = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
cboNacionalidad = new javax.swing.JComboBox<>();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Cliente");
jLabel1.setText("Nombre");
jLabel2.setText("Profesion");
tblCliente.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}
},
new String [] {
"Id", "Nombre", "Apellido", "Telefono", "Profesion", "Nacionalidad"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane1.setViewportView(tblCliente);
jButton1.setText("Agregar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel3.setText("Apellido");
jLabel4.setText("Telefono");
jLabel5.setText("Nacionalidad");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(61, 61, 61)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addGap(44, 44, 44)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtNombre, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE)
.addComponent(txtApellido))
.addGap(49, 49, 49)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(txtTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(cboNacionalidad, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cboDistrito, javax.swing.GroupLayout.Alignment.LEADING, 0, 225, Short.MAX_VALUE))))
.addGroup(layout.createSequentialGroup()
.addGap(44, 44, 44)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 524, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(40, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(txtNombre, 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.LEADING)
.addComponent(jLabel3)
.addComponent(txtApellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txtTelefono, 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(cboDistrito, 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(jLabel5)
.addComponent(cboNacionalidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(21, 21, 21)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(23, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
ClienteService clienteService = ServiceLocate.getClienteService();
Cliente cliente = new Cliente();
cliente.setNombre(this.txtNombre.getText());
cliente.setApellido(this.txtApellido.getText());
cliente.setTelefono(this.txtTelefono.getText());
Distrito distrito = new Distrito();
distrito.setId(listaDistrito.get(this.cboDistrito.getSelectedIndex()).getId());
cliente.setDistrito(distrito);
Nacionalidad nacionalidad = new Nacionalidad();
nacionalidad.setId(listaNacionalidad.get(this.cboNacionalidad.getSelectedIndex()).getId());
cliente.setNacionalidad(nacionalidad);
clienteService.crear(cliente);
this.txtNombre.setText("");
this.txtApellido.setText("");
this.txtTelefono.setText("");
this.cboDistrito.setSelectedIndex(0);
this.cboNacionalidad.setSelectedIndex(0);
this.txtNombre.requestFocus();
JOptionPane.showMessageDialog(this, "Profesor Registrado");
cargarClientes();
}
/**
* @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(UICliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(UICliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(UICliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(UICliente.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 UICliente().setVisible(true);
}
});
}