0% encontró este documento útil (0 votos)
80 vistas25 páginas

Reto 5 - 2

Este documento contiene código Java para la conexión a una base de datos MySQL y el manejo de datos de productos en tablas. Se define una clase Conexión para establecer la conexión a la BD. Luego, se definen clases Producto y ControladorProductos con métodos para consultar, agregar, modificar y eliminar registros de productos. Finalmente, se incluye un formulario Swing para interactuar con los datos.

Cargado por

john
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
80 vistas25 páginas

Reto 5 - 2

Este documento contiene código Java para la conexión a una base de datos MySQL y el manejo de datos de productos en tablas. Se define una clase Conexión para establecer la conexión a la BD. Luego, se definen clases Producto y ControladorProductos con métodos para consultar, agregar, modificar y eliminar registros de productos. Finalmente, se incluye un formulario Swing para interactuar con los datos.

Cargado por

john
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 25

Conexión a la base de datos

package Modelo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Conexion
{

//Definimos las variables o atributos necesarios


private Connection con;
private static final String host = "localhost"; //Nombre del
equipo en donde está la BD
private static final String bd = "farmacia"; //Nombre de la BD a
trabajar
private static final String user = "root"; //Nombre del usuario de
la BD
private static final String password = "Nemesis21"; //Clave del
usuario de MYSQL
private static final String url = "jdbc:mysql://" + host + "/" +
bd; private static final String driver =
"com.mysql.cj.jdbc.Driver";
//Creamos un método para activar o abrir la conexión con la BD y
el Driver public Conexion() { try {

Class.forName(driver);
try {
//Aquí se indica con que credenciales se va a conectra
a la BD
con = DriverManager.getConnection(url, user,
password);
} catch (SQLException ex) {

Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null,
ex);
}
} catch (ClassNotFoundException ex) {

Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null,
ex);
}
}

//Creamos un método que retorne la conección


public Connection getCon() { return con;
} public void desconectar () {
try { if (this.getCon() !=
null) { //Esta abierta
la BD con.close();

}
} catch (SQLException ex) {

Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null,
ex);
System.out.println("Ocurrió un error al cerrar la Base de
Datos " + ex.getMessage().toString());
}
}
}
clase producto

package Modelo;
public class Producto {
private String nombre;
private int id; private
float temperatura; private
float valorbase;

public Producto (String nombre, int id, float temperatura, float


valorbase) { this.nombre = nombre; this.id = id;
this.temperatura = temperatura; this.valorbase = valorbase;
}
public Producto ()
{
} public String
getNombre() { return
nombre;
} public int
getId () { return
id;
} public float
getTemperatura() { return
temperatura;
} public float
getValorbase() { return
valorbase;
} public void setNombre(String
nombre) { this.nombre = nombre;
} public void
setId(int id) { this.id
= id;
}

public void setTemperatura(float temperatura) {


this.temperatura = temperatura;
} public void setValorbase(float
valorbase) { this.valorbase =
valorbase;
}
}

Controlador producto

package Controlador;
import Modelo.Conexion; import
java.sql.ResultSet; import
java.sql.SQLException; import
java.sql.Statement; import
java.util.ArrayList; import
java.util.logging.Level; import
java.util.logging.Logger; import
Modelo.Producto;
public class Controlador_Productos
{
//1.Creamos un método para visualziar todos los registros de la
tabla Productos public ArrayList<Producto> ver_productos() {
ArrayList<Producto> lista_productos = new ArrayList(); try
{
Conexion conector = new Conexion();
String cadena = "Select * from productos order by nombre";
Statement smt = conector.getCon().createStatement();
ResultSet rs; rs = smt.executeQuery(cadena);
while (rs.next()) {
Producto medicamento = new Producto();
medicamento.setNombre(rs.getString("nombre"));
medicamento.setId(rs.getInt("id"));

medicamento.setTemperatura(rs.getFloat("temperatura"));
medicamento.setValorbase(rs.getFloat("valorbase"));
lista_productos.add(medicamento);
}

} catch (SQLException ex) {

Logger.getLogger(Controlador_Productos.class.getName()).log(Level.SEVE
RE, null, ex); }
return lista_productos;

//3.Creamos un método que nos permita ingresar un producto nuevo


en la tabla
public String agregarProducto(String nombre,int id, float
temperatura, float valor) { String mensaje = "";
try {

Conexion conector = new Conexion();


String cadena = "Insert into Productos values ('" + nombre
+ "'," + id + "," + temperatura + "," + valor + ")";
Statement stm = conector.getCon().createStatement();
stm.executeUpdate(cadena); mensaje = "Registro
exitoso.";
} catch (SQLException ex) {

Logger.getLogger(Controlador_Productos.class.getName()).log(Level.SEVE
RE, null, ex);
mensaje = "Error al registrar el producto: " +
ex.getMessage().toString();
}
return mensaje;
}

//4.Creamos un método que nos permita modificar un producto en la


tabla
public String modificarProducto(String nombre,int id, float
temperatura, float valor) { String mensaje = "";
try {

Conexion conector = new Conexion();


String cadena = "Update productos set nombre='" + nombre +
"',temperatura=" + temperatura + ", valorbase=" + valor + " where id="
+ id;
Statement stm = conector.getCon().createStatement();
stm.executeUpdate(cadena); mensaje = "Actualziación
exitosa.";
} catch (SQLException ex) {

Logger.getLogger(Controlador_Productos.class.getName()).log(Level.SEVE
RE, null, ex);
mensaje = "Error al actualizar el producto: " +
ex.getMessage().toString();
}
return mensaje;
}
//4.Creamos un método que nos permita eliminar un producto en la
tabla public String eliminarProducto(int codigo) {
String mensaje = ""; try {

Conexion conector = new Conexion();


String cadena = "Delete from productos where id=" +
codigo;
Statement stm = conector.getCon().createStatement();
stm.executeUpdate(cadena); mensaje = "Eliminación
exitosa.";
} catch (SQLException ex) {
Logger.getLogger(Controlador_Productos.class.getName()).log(Level.SEVE
RE, null, ex);
mensaje = "Error al Eliminar el producto: " +
ex.getMessage().toString();
}
return mensaje;
}

//2.Ahora creamos un método para visualziar un solo producto


public ArrayList<Producto> ver_producto(int codigo) {
ArrayList<Producto> lista_producto = new ArrayList(); try
{

Conexion conector = new Conexion();


String cadena = "Select * from productos where id=" +
codigo;
Statement smt = conector.getCon().createStatement();
ResultSet rs; rs = smt.executeQuery(cadena);
while (rs.next()) {
Producto prod = new Producto();
prod.setNombre(rs.getString("nombre"));
prod.setId(Integer.parseInt(rs.getString("id")));

prod.setTemperatura(Float.parseFloat(rs.getString("temperatura")));

prod.setValorbase(Float.parseFloat(rs.getString("valorbase")));
lista_producto.add(prod);

} catch (SQLException ex) {

Logger.getLogger(Controlador_Productos.class.getName()).log(Level.SEVE
RE, null, ex); }
return lista_producto;
}
}
Formulario producto

Código formulario

package Vista;
import java.util.ArrayList; import
javax.swing.table.DefaultTableModel; import
Controlador.Controlador_Productos; import
Modelo.Producto; import
javax.swing.JOptionPane;
public class Formulario_Producto extends javax.swing.JFrame
{ Controlador_Productos producto = new
Controlador_Productos();
public
Formulario_Producto() {
initComponents();
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
txtid = new javax.swing.JTextField();
txttemperatura = new javax.swing.JTextField();
btnguardar = new javax.swing.JButton();
btnactualizar = new javax.swing.JButton();
btneliminar = new javax.swing.JButton(); jLabel1 = new
javax.swing.JLabel(); btnconsultar = new
javax.swing.JButton(); jLabel2 = new
javax.swing.JLabel(); jScrollPane1 = new
javax.swing.JScrollPane(); tbldatos = new
javax.swing.JTable(); jLabel3 = new
javax.swing.JLabel(); jLabel4 = new
javax.swing.JLabel(); txtnombre = new
javax.swing.JTextField(); txtvalorbase = new
javax.swing.JTextField(); jPanel1 = new
javax.swing.JPanel(); jLabel5 = new
javax.swing.JLabel(); jPanel2 = new
javax.swing.JPanel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
txtid.setFont(new java.awt.Font("Tahoma", 1, 18)); //
NOI18N

txttemperatura.setFont(new java.awt.Font("Tahoma", 1, 18)); //


NOI18N
btnguardar.setFont(new java.awt.Font("Tahoma", 1, 18)); //
NOI18N btnguardar.setText("Guardar");
btnguardar.addActionListener(new
java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent
evt) { btnguardarActionPerformed(evt);
}
});
btnactualizar.setFont(new java.awt.Font("Tahoma", 1, 18)); //
NOI18N btnactualizar.setText("Actualizar");
btnactualizar.addActionListener(new
java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent
evt) { btnactualizarActionPerformed(evt);
}
});

btneliminar.setFont(new java.awt.Font("Tahoma", 1, 18)); //


NOI18N btneliminar.setText("Eliminar");
btneliminar.addActionListener(new
java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent
evt) { btneliminarActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); //
NOI18N

jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel1.setText("Nombre");

btnconsultar.setFont(new java.awt.Font("Tahoma", 1, 18)); //


NOI18N
btnconsultar.setText("Consultar");
btnconsultar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent
evt) { btnconsultarActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 18)); //
NOI18N

jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel2.setText("Id");
tbldatos.setModel(new
javax.swing.table.DefaultTableModel( new Object [][] {

},
new String [] {
"Nombre", "Id", "Temperatura", "Valor Base"
} ));
jScrollPane1.setViewportView(tbldatos);
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18)); //
NOI18N

jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel3.setText("Temperatura");

jLabel4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N

jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel4.setText("Valorbase");

txtnombre.setFont(new java.awt.Font("Tahoma", 1, 18)); //


NOI18N
txtvalorbase.setFont(new java.awt.Font("Tahoma", 1, 18)); //
NOI18N jPanel1.setBackground(new java.awt.Color(0, 102,
204));
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 24)); //
NOI18N jLabel5.setForeground(new java.awt.Color(255, 255,
255)); jLabel5.setText("Sistema para el manejo de una
Farmacia");

javax.swing.GroupLayout jPanel1Layout = new


javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(

jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LE
ADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(158, 158, 158)
.addComponent(jLabel5)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(

jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LE
ADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jLabel5)
.addContainerGap(63, Short.MAX_VALUE))
); jPanel2.setBackground(new java.awt.Color(0,
102, 204));

javax.swing.GroupLayout jPanel2Layout = new


javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(

jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LE
ADING)
.addGap(0, 867, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(

jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LE
ADING)
.addGap(0, 100, 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()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment
.TRAILING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment
.LEADING, false)
.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment
.TRAILING)
.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment
.TRAILING)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment
.LEADING)
.addComponent(jLabel1,
javax.swing.GroupLayout.PREFERRED_SIZE, 121,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment
.TRAILING, false)

.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING)))
.addComponent(jLabel4,
javax.swing.GroupLayout.PREFERRED_SIZE, 118,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment
.TRAILING)

.addComponent(txttemperatura, javax.swing.GroupLayout.PREFERRED_SIZE,
230, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtid,
javax.swing.GroupLayout.PREFERRED_SIZE, 230,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtnombre,
javax.swing.GroupLayout.PREFERRED_SIZE, 230,
javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(txtvalorbase, javax.swing.GroupLayout.PREFERRED_SIZE,
230, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment
.LEADING, false)
.addComponent(btnguardar,
javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnactualizar,
javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btneliminar,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnconsultar,
javax.swing.GroupLayout.PREFERRED_SIZE, 123,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(jScrollPane1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel1,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap(78, Short.MAX_VALUE))
);
layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment
.TRAILING)
.addComponent(jScrollPane1,
javax.swing.GroupLayout.PREFERRED_SIZE, 335,
javax.swing.GroupLayout.PREFERRED_SIZE)

.addGroup(javax.swing.GroupLayout.Alignment.LEADING,
layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment
.BASELINE)
.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
.BASELINE)
.addComponent(jLabel2)
.addComponent(txtid,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment
.BASELINE)
.addComponent(jLabel3)
.addComponent(txttemperatura,
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(txtvalorbase,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(36, 36, 36)
.addComponent(btnguardar)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnactualizar)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btneliminar)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnconsultar)))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
23, Short.MAX_VALUE)
.addComponent(jPanel2,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>

private void btnguardarActionPerformed(java.awt.event.ActionEvent


evt) { if
(this.txtnombre.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Digite por favor el
nombre del producto.");
} else if (this.txtid.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Digite por favor el
id del producto.");
} else if (this.txttemperatura.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Digite por favor la
temperatura del producto.");
} else if (this.txtvalorbase.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Digite por favor el
valor base del producto.");
} else { int id =
Integer.parseInt(this.txtid.getText()); String
nombre = this.txtnombre.getText();
float temperatura
=Float.parseFloat(this.txttemperatura.getText());
float valorbase
=Float.parseFloat(this.txtvalorbase.getText());
String mensaje = producto.agregarProducto(nombre,id,
temperatura, valorbase);
JOptionPane.showMessageDialog(null, mensaje);
mostrarTabla();

}
}

private void
btnactualizarActionPerformed(java.awt.event.ActionEvent evt) {
if (this.txtnombre.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Digite por favor el
nombre del producto.");
} else if (this.txtid.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Digite por favor el
id del producto.");
} else if (this.txttemperatura.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Digite por favor la
temperatura del producto.");
} else if (this.txtvalorbase.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Digite por favor el
valor base del producto.");
} else { int id =
Integer.parseInt(this.txtnombre.getText()); String
nombre = this.txtid.getText();
float temperatura
=Float.parseFloat(this.txttemperatura.getText());
float valorbase
=Float.parseFloat(this.txtvalorbase.getText());
String mensaje =
producto.modificarProducto(nombre,id,temperatura,valorbase);
JOptionPane.showMessageDialog(null, mensaje);
mostrarTabla();

}
}

private void btneliminarActionPerformed(java.awt.event.ActionEvent


evt) {
if (this.txtid.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Digite por favor el
id del producto."); } else { int id =
Integer.parseInt(this.txtid.getText()); String mensaje =
producto.eliminarProducto(id);
JOptionPane.showMessageDialog(null, mensaje);
mostrarTabla();

}
}

private void
btnconsultarActionPerformed(java.awt.event.ActionEvent evt) {
int codigo=0; if (this.txtid.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Debe Digitar el id
para hacer la búsqueda");
} else {
codigo=Integer.parseInt(this.txtid.getText());
String datos[] = new String[4];
DefaultTableModel Tabla_productos = new
DefaultTableModel();
Tabla_productos = (DefaultTableModel) tbldatos.getModel();
//Limpiar la tabla
for (int x = Tabla_productos.getRowCount() - 1; x >= 0; x-
) {
Tabla_productos.removeRow(x);
}
//Ahora la llenamos
ArrayList<Producto> listaproducto = new ArrayList();
listaproducto = producto.ver_producto(codigo); for
(Producto x : listaproducto) { datos[0] =
x.getNombre(); datos[1] =
String.valueOf(x.getId()); datos[2] =
String.valueOf(x.getTemperatura()); datos[3] =
String.valueOf(x.getValorbase());

Tabla_productos.addRow(datos);
}
Tabla_productos = (DefaultTableModel) tbldatos.getModel();
}
}
public void
mostrarTabla() {
String datos[] = new String[4];
DefaultTableModel Tabla_productos = new DefaultTableModel();
Tabla_productos = (DefaultTableModel) tbldatos.getModel();
//Limpiar la tabla for (int x =
Tabla_productos.getRowCount() - 1; x >= 0; x--) {
Tabla_productos.removeRow(x);
}
//Ahora la llenamos
ArrayList<Producto> listaautor = new ArrayList();
listaautor = producto.ver_productos();

for (Producto x : listaautor) {


datos[0] = x.getNombre(); datos[1] =
String.valueOf(x.getId()); datos[2] =
String.valueOf(x.getTemperatura()); datos[3] =
String.valueOf(x.getValorbase());
Tabla_productos.addRow(datos);
}
Tabla_productos = (DefaultTableModel) tbldatos.getModel();
}
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.ht
ml */ 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(Formulario_Producto.class.getName()
).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(Formulario_Producto.class.getName()
).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(Formulario_Producto.class.getName()
).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(Formulario_Producto.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
Formulario_Producto().setVisible(true);
}
});
}

// Variables declaration - do not modify


private javax.swing.JButton btnactualizar;
private javax.swing.JButton btnconsultar; private
javax.swing.JButton btneliminar;

private javax.swing.JButton btnguardar;


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.JPanel jPanel1; private
javax.swing.JPanel jPanel2; private
javax.swing.JScrollPane jScrollPane1; private
javax.swing.JTable tbldatos; private
javax.swing.JTextField txtid; private
javax.swing.JTextField txtnombre; private
javax.swing.JTextField txttemperatura; private
javax.swing.JTextField txtvalorbase;
// End of variables declaration
}

También podría gustarte