InicioCiencia EducacionTabla de arreglos en Java Insertar, imprimir, borrar registr







package tabla.mundo;

/**
* clase que genera una matriz que puede crecer y reducirse en tiempo
* de ejecucion, y hacer operaciones basicas como:<br>
* <b>ingresar registros<br>
* mostrar registros<br>
* borrar registros<br></b>
* entre otras cosas.
*/
public class Tabla {

/**
* matriz que contendra todos los datos(registros).
*/
private Object [][] tabla;

/**
* vector usado cuando se encuentra un registros buscado.
*/
private Object [] darRegistro;

/**
* numero de columnas de la tabla.
*/
private int numCols;

/**
* constructor que inicializa la cantidad de
* columnas que tendra la tabla(matriz).
*
* @param numCols
*/
public Tabla(int numCols)
{
this.numCols = numCols;
this.tabla = new Object[0][numCols];
}

/**
* este metodo es el que guarda la informacion e incrementa el tamaño de
* la matriz a medida que se le agregan registros.
*
* @param registro
*/
public void add(Object [] registro)
{
/**
* se crea una tabla auxiliar exatamente del mismo tamanio de
* la tabla original para contener los datos temporalmente.
*/
Object [][] tablaAux = new Object[tabla.length][numCols];

/**
* se pasan todos los datos de la tabla original a la tabla auxiliar.
*/
for(int f=0; f<tabla.length; f++)
{
for(int c=0; c<tabla[0].length; c++)
{
tablaAux[f][c] = tabla[f][c];
}
}

/**
* se redimensiona la tabla original aumentandole una fila para
* guardar el nuevo registro, (este proceso reinicia toda la
* tabla y se borran los datos por eso es nesesario la tabla auxiliar).
*/
tabla = new Object[(tablaAux.length + 1)][numCols];

/**
* se vuelven a pasar los datos de la tabla auxiliar a la tabla original.
*/
for(int f=0; f<tablaAux.length; f++)
{
for(int c=0; c<tablaAux[0].length; c++)
{
tabla[f][c] = tablaAux[f][c];
}
}

/**
* por ultimo se agrega el nuevo registro en la ultima fila
* de la tabla, ya que esta esta vacia que esta vacia por
* que esta tabla ahora tiene una fila mas que antes asi
* que al pasar los datos esta quedo vacia.
*/
for(int c=0; c<tabla[0].length; c++)
{
tabla[tablaAux.length][c] = registro[c];
}
}

/**
* el dato pasado por parametro es buscado con un for en la
* columna pasada por parametro, si el dato es encontrado se
* retorna un valor verdadero(true), ya depende de las
* nesesidades del programador que decide hacer con ese resultado.
*
* @param dato
* @param col
* @return estado
*/
public boolean check(Object dato, int col)
{
boolean estado = false;

for(int f=0; f<tabla.length; f++)
{
Object aux = tabla[f][col];

if(aux.equals(dato))
{
estado = true;
break;
}
}

return estado;
}

/**
* buscar un dato segun la columna (0 es la primer columna, no 1)
* si encuentra el dato retornara un valor booleano verdadero
* y llenara un vector con los datos del registro encontrado
* y con eso es posible llamar al metodo darDato(int col) para
* que muestre el dato deseado de ese registro.
*
* @param dato
* @param columna
* @return estado
*/
public boolean seek(Object dato, int columna)
{
boolean estado = false;

darRegistro = new Object [numCols];

for(int f=0; f<tabla.length; f++)
{
Object aux = tabla[f][columna];

if(aux.equals(dato))
{
for(int c=0; c<numCols; c++)
{
darRegistro[c] = tabla[f][c];
}

estado = true;
break;
}
}

return estado;
}

/**
* este metodo modifica un registro el primer parametro es para ingresar
* el dato a buscar, el segundo es para indicar en que columna debe buscar,
* y el tercer parametro es para ingresar el vector con los nuevos datos.
*
* @param dato
* @param col
* @param nuevosDatos
* @return estado
*/
public boolean update(Object dato, int col, Object [] nuevosDatos)
{
boolean estado = false;

for(int f=0; f<tabla.length; f++)
{
Object aux = tabla[f][col];

if(aux.equals(dato))
{
for(int c=0; c<numCols; c++)
{
tabla[f][c] = nuevosDatos[c];
}

estado = true;
}
}

return estado;
}

/**
* este metodo borra un registro de la tabla siempre y cuando se
* encuentre el dato ingresado por parametro en la columna seleccionada.
*
* @param dato
* @param col
* @return estado
*/
public boolean delete(Object dato, int col)
{
boolean estado = false;
int fila = 0;

if(this.check(dato, col))
{
Object [][] tablaAux = new Object[tabla.length - 1][numCols];

for(int f=0; f<tabla.length; f++)
{
Object aux = tabla[f][col];

if(aux.equals(dato))
{
continue;
}
else
{
for(int c=0; c<numCols; c++)
{
tablaAux[fila][c] = tabla[f][c];
}

fila++;
}
}

tabla = new Object[tablaAux.length][numCols];

for(int f=0; f<tabla.length; f++)
{
for(int c=0; c<tabla[0].length; c++)
{
tabla[f][c] = tablaAux[f][c];
}
}

estado = true;
}

return estado;
}

/**
* este metodo devuelve un String donde esta toda la tabla para poder
* imprimirla por consola o colocarla en una interfaz grafica.
*
* @return String tabla
*/
public String getPrintTable()
{
String aux = "";

for(int f=0; f<tabla.length; f++)
{
for(int c=0; c<tabla[0].length; c++)
{
aux += tabla[f][c] + "t";
}

aux += "n";
}

return aux;
}

/**
* este metodo lo que hace es pasar un vector o lista
* con todos los datos de la columna que elija.
*
* @param col
* @return [] lista de una columna
*/
public Object [] getList(int col)
{
Object [] lista = new Object [tabla.length];

if(tabla.length > 0)
{
for(int f=0; f<tabla.length; f++)
{
lista[f] = tabla[f][col];
}
}

return lista;
}

/**
* este metodo se debe usar en conjunto con el metodo buscar ya que si el
* metodo seek() encuentra el registro lo pasara a este metodo.
*
* @param posicion
* @return [] registro encontrado con el metodo seek()
*/
public Object getDate(int posicion)
{
return darRegistro[posicion];
}

/**
* este metodo entrega la tabla entera en una matriz,
* util para colocarla en un JTable.
*
* @return tabla
*/
public Object[][] getTable()
{
return tabla;
}

/**
* devuelve el numero de registros que tiene la tabla.
*
* @return numero de filas o registros
*/
public int getNumRows()
{
return tabla.length;
}

/**
* devuelve el numero de columnas que tiene la tabla.
*
* @return numero de columnas
*/
public int getNumColumns()
{
return tabla[0].length;
}

}



package tabla.interfaz;

import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.table.*;
import tabla.mundo.Tabla;

public class Ventana extends JFrame implements ActionListener, ChangeListener, ListSelectionListener{

private Tabla miTabla;
private int paso;
private final String [] cols = {"Cedula","Apellido","Nombre","Edad","Direccion","Telefono"};

private JRadioButton rb1,rb2,rb3,rb4,rb5,rb6;
private JButton bt1,bt2,bt3,bt4,bt5,bt6;
private JTextField txf1,txf2,txf3,txf4,txf5,txf6;
private JLabel lb1,lb2,lb3,lb4,lb5,lb6,lb7;
private JList lista;
private JScrollPane scrlp;
private JTable tabla;
private DefaultTableModel mdlt;
private JSpinner spin;
private SpinnerNumberModel spinModel;

public Ventana()
{
super("Tabla Arreglos";

miTabla = new Tabla(6);
paso = 0;

this.getContentPane().setLayout(null);
this.getContentPane().add(this.pnlOpciones());
this.getContentPane().add(this.pnlLista());
this.getContentPane().add(this.pnlForm());
this.getContentPane().add(this.pnlTabla());
this.getContentPane().setBackground(new Color(155,193,232));

this.desabilitar();

this.setSize(800,615);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setVisible(true);

this.addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
dispose();
}
});
}

private JPanel pnlOpciones()
{
rb1 = new JRadioButton("Agregar";
rb2 = new JRadioButton("Buscar";
rb3 = new JRadioButton("Ver 1-2-3...";
rb4 = new JRadioButton("Modificar";
rb5 = new JRadioButton("Borrar";
rb6 = new JRadioButton("Lista";

rb1.setSelected(true);

rb1.addChangeListener(this);
rb2.addChangeListener(this);
rb3.addChangeListener(this);
rb4.addChangeListener(this);
rb5.addChangeListener(this);
rb6.addChangeListener(this);

ButtonGroup grupo = new ButtonGroup();
grupo.add(rb1);
grupo.add(rb2);
grupo.add(rb3);
grupo.add(rb4);
grupo.add(rb5);
grupo.add(rb6);

rb1.setOpaque(false);
rb2.setOpaque(false);
rb3.setOpaque(false);
rb4.setOpaque(false);
rb5.setOpaque(false);
rb6.setOpaque(false);

int x = 20;
int y = 30;
int w = 100;//ancho
int h = 30;//alto
int i = 43;//incremento

rb1.setBounds(x,y,w,h);
rb2.setBounds(x,y+=i,w,h);
rb3.setBounds(x,y+=i,w,h);
rb4.setBounds(x,y+=i,w,h);
rb5.setBounds(x,y+=i,w,h);
rb6.setBounds(x,y+=i,w,h);

JPanel pnl = new JPanel();
pnl.setLayout(null);
pnl.setBounds(20, 285, 140, 280);
pnl.setBorder(BorderFactory.createTitledBorder("Opciones");
pnl.setOpaque(false);

pnl.add(rb1);
pnl.add(rb2);
pnl.add(rb3);
pnl.add(rb4);
pnl.add(rb5);
pnl.add(rb6);

return pnl;
}

private JPanel pnlLista()
{
lista = new JList();
lista.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lista.addListSelectionListener(this);
scrlp = new JScrollPane(lista);
scrlp.setBounds(10,20,220,230);

JPanel pnl = new JPanel();
pnl.setLayout(null);
pnl.setBounds(20, 15, 240, 260);
pnl.setBorder(BorderFactory.createTitledBorder("Lista");
pnl.setOpaque(false);

pnl.add(scrlp);

return pnl;
}

private JPanel pnlTabla()
{
mdlt = new DefaultTableModel();
mdlt.setColumnIdentifiers(cols);
tabla = new JTable(mdlt);
tabla.setRowSorter(new TableRowSorter(mdlt));
scrlp = new JScrollPane(tabla);
scrlp.setBounds(10,20,575,250);

JPanel pnl = new JPanel();
pnl.setLayout(null);
pnl.setBounds(180, 285, 595, 280);
pnl.setBorder(BorderFactory.createTitledBorder("Tabla");
pnl.setOpaque(false);

pnl.add(scrlp);

return pnl;
}

private JPanel pnlForm()
{
lb1 = new JLabel("Buscar";
lb2 = new JLabel("Cedula";
lb3 = new JLabel("Apellido(s)";
lb4 = new JLabel("Nombre(s)";
lb5 = new JLabel("Edad";
lb6 = new JLabel("Direccion";
lb7 = new JLabel("Telefono";

txf1 = new JTextField();//buscar
txf2 = new JTextField();//cedula
txf3 = new JTextField();//apellido
txf4 = new JTextField();//nombre
txf5 = new JTextField();//direccion
txf6 = new JTextField();//telefono

spinModel = new SpinnerNumberModel(1,1,100,1);
spin = new JSpinner(spinModel);//edad

bt1 = new JButton("=>";
bt2 = new JButton("Ejecutar";//agregar-borrar-modificar
bt3 = new JButton("|<";//primero
bt4 = new JButton("<<";//anterior
bt5 = new JButton(">>";//siguiente
bt6 = new JButton(">|";//ultimo

bt1.setToolTipText("ejecutar busqueda";
bt2.setToolTipText("agregar - borrar - modificar registros (depende de que opcion este activada)";
bt3.setToolTipText("primer registro";
bt4.setToolTipText("anterior registro";
bt5.setToolTipText("siguiente registro";
bt6.setToolTipText("ultimo registro";

bt1.addActionListener(this);
bt2.addActionListener(this);
bt3.addActionListener(this);
bt4.addActionListener(this);
bt5.addActionListener(this);
bt6.addActionListener(this);

txf1.setBackground(Color.white);
txf2.setBackground(Color.white);
txf3.setBackground(Color.white);
txf4.setBackground(Color.white);
txf5.setBackground(Color.white);
txf6.setBackground(Color.white);
spin.setBackground(Color.white);

int x = 20;//eje x
int y = 30;//eje y
int w = 60;//ancho
int h = 30;//alto
int i = 43;//incremento

lb1.setBounds(x,y,w,h);
lb2.setBounds(x,y+=i,w,h);
lb3.setBounds(x,y+=i,w,h);
lb4.setBounds(x,y+=i,w,h);

x = 90; y = 30; w = 120;

txf1.setBounds(x,y,w,h);
txf2.setBounds(x,y+=i,w,h);
txf3.setBounds(x,y+=i,w,h);
txf4.setBounds(x,y+=i,w,h);

x = 250; y = 30; w = 60;

bt1.setBounds(220,y,50,h);
lb5.setBounds(x,y+=i,w,h);
lb6.setBounds(x,y+=i,w,h);
lb7.setBounds(x,y+=i,w,h);

x = 320; y = 30; w = 120;

spin.setBounds(x,y+=i,50,h);
txf5.setBounds(x,y+=i,w,h);
txf6.setBounds(x,y+=i,w,h);

x = 50;

bt2.setBounds(x,y+=50,100,h);

x = 120; w = 50; i = 60;

bt3.setBounds(x+=i,y,w,h);
bt4.setBounds(x+=i,y,w,h);
bt5.setBounds(x+=i,y,w,h);
bt6.setBounds(x+=i,y,w,h);

JPanel pnl = new JPanel();
pnl.setLayout(null);
pnl.setBounds(280, 15, 495, 260);
pnl.setBorder(BorderFactory.createTitledBorder("Formulario");
pnl.setOpaque(false);

pnl.add(lb1);
pnl.add(lb2);
pnl.add(lb3);
pnl.add(lb4);
pnl.add(lb5);
pnl.add(lb6);
pnl.add(lb7);
pnl.add(bt1);
pnl.add(txf1);
pnl.add(txf2);
pnl.add(txf3);
pnl.add(txf4);
pnl.add(spin);
pnl.add(txf5);
pnl.add(txf6);
pnl.add(bt2);
pnl.add(bt3);
pnl.add(bt4);
pnl.add(bt5);
pnl.add(bt6);

return pnl;
}

private void borrar()
{
txf1.setText("";
txf2.setText("";
txf3.setText("";
txf4.setText("";
txf5.setText("";
txf6.setText("";
spin.setValue(1);
}

private void desabilitar()
{
bt1.setEnabled(false);
bt2.setEnabled(false);
bt3.setEnabled(false);
bt4.setEnabled(false);
bt5.setEnabled(false);
bt6.setEnabled(false);

txf1.setEditable(false);
txf2.setEditable(false);
txf3.setEditable(false);
txf4.setEditable(false);
txf5.setEditable(false);
txf6.setEditable(false);
lista.setEnabled(false);
spin.setEnabled(false);
}

private void verInfo()
{
txf2.setText((String)miTabla.getDate(0));
txf3.setText((String)miTabla.getDate(1));
txf4.setText((String)miTabla.getDate(2));
spin.setValue(miTabla.getDate(3));
txf5.setText((String)miTabla.getDate(4));
txf6.setText("" + miTabla.getDate(5));
}

private void mensaje(int opc)
{
switch(opc)
{
case 0:
JOptionPane.showMessageDialog(this,
"No se pudo realizar la operacion.",
"FALLO",JOptionPane.WARNING_MESSAGE);
break;

case 1:
JOptionPane.showMessageDialog(this, "No se puede seguir.",
"ATENCION", JOptionPane.WARNING_MESSAGE);
break;

case 2:
JOptionPane.showMessageDialog(this,
"Alguna casilla nesesaria esta vacia.",
"ATENCION", JOptionPane.WARNING_MESSAGE);
break;

case 3:
JOptionPane.showMessageDialog(this,
"No se encontro el registro.",
"FALLO", JOptionPane.WARNING_MESSAGE);
break;

case 4:
JOptionPane.showMessageDialog(this, "Listo tabla actualizada.",
"LISTO", JOptionPane.INFORMATION_MESSAGE);
break;

case 5:
JOptionPane.showMessageDialog(this,
"El registro ya existe no se puede guardar",
"FALLO", JOptionPane.WARNING_MESSAGE);
break;

case 6:
JOptionPane.showMessageDialog(null,
"Error numerico verifique sus datos",
"ERROR", JOptionPane.ERROR_MESSAGE);
break;
}
}

public void valueChanged(ListSelectionEvent e)
{
Object f = e.getSource();

if(f.equals(lista))
{
miTabla.seek((String)lista.getSelectedValue(), 0);
this.verInfo();
}
}

public void stateChanged(ChangeEvent e)
{
Object f = e.getSource();

if(f.equals(rb1))//agregar
{
if(rb1.isSelected())
{
this.desabilitar();
txf2.setEditable(true);
txf3.setEditable(true);
txf4.setEditable(true);
txf5.setEditable(true);
txf6.setEditable(true);
spin.setEnabled(true);
bt2.setEnabled(true);
}
}
if(f.equals(rb2))//buscar
{
if(rb2.isSelected())
{
this.desabilitar();
txf1.setEditable(true);
bt1.setEnabled(true);
}
}
if(f.equals(rb3))//ver 1-2-3...
{
if(rb3.isSelected())
{
this.desabilitar();
bt3.setEnabled(true);
bt4.setEnabled(true);
bt5.setEnabled(true);
bt6.setEnabled(true);
}
}
if(f.equals(rb4))//modificar
{
if(rb4.isSelected())
{
this.desabilitar();
txf1.setEditable(true);
bt1.setEnabled(true);
}
}
if(f.equals(rb5))//borrar
{
if(rb5.isSelected())
{
this.desabilitar();
bt1.setEnabled(true);
txf1.setEditable(true);
}
}
if(f.equals(rb6))//lista
{
if(rb6.isSelected())
{
this.desabilitar();
lista.setEnabled(true);
}
}

this.borrar();
}

public void actionPerformed(ActionEvent e)
{
Object f = e.getSource();

if(f.equals(bt1))//buscar
{
if(!txf1.getText().equals("")
{

if(miTabla.seek(txf1.getText(), 0))
{
this.verInfo();

if(rb4.isSelected())//modificar
{
txf2.setEditable(true);
txf3.setEditable(true);
txf4.setEditable(true);
txf5.setEditable(true);
txf6.setEditable(true);
spin.setEnabled(true);
bt2.setEnabled(true);
}
if(rb5.isSelected())//borrar
{
bt2.setEnabled(true);
}
}
else
{
this.mensaje(3);
}
}
else
{
this.mensaje(2);
}
}

if(f.equals(bt2))//ejecutar
{
if(rb1.isSelected())//agregar
{
try
{
long id = Long.parseLong(txf2.getText());
int edad = (Integer)spin.getValue();
long tel = Long.parseLong(txf6.getText());

Object [] reg = {txf2.getText(), txf3.getText().toLowerCase(),
txf4.getText().toLowerCase(), edad,
txf5.getText().toLowerCase(), tel};

if(miTabla.check(txf2.getText(), 0) == false)
{
miTabla.add(reg);

this.mensaje(4);
this.borrar();
}
else
{
this.mensaje(5);
}
}
catch(NumberFormatException ex)
{
this.mensaje(6);
}
}
else if(rb4.isSelected())//modificar
{

try
{
long id = Long.parseLong(txf2.getText());
int edad = (Integer)spin.getValue();
long tel = Long.parseLong(txf6.getText());

Object [] reg = {txf2.getText(), txf3.getText().toLowerCase(),
txf4.getText().toLowerCase(), edad,
txf5.getText().toLowerCase(), tel};

if(miTabla.update(txf1.getText(), 0, reg))
{
this.mensaje(4);
this.borrar();
}
else
{
this.mensaje(5);
}
}
catch(NumberFormatException ex)
{
this.mensaje(6);
}
}
else if(rb5.isSelected())//borrar
{
int resp = JOptionPane.showConfirmDialog(null,
"¿Realmente desea borrar este registro?",
"Confirme",JOptionPane.YES_NO_OPTION);
if(resp == JOptionPane.YES_OPTION)
{
miTabla.delete(txf1.getText(), 0);
this.mensaje(4);
this.borrar();
}
else
{
this.mensaje(0);
}
}
}

if(f.equals(bt3))//primero
{
if(miTabla.getList(0).length > 0)
{
paso = 0;
miTabla.seek(miTabla.getList(0)[0], 0);
this.verInfo();
}
else
{
this.mensaje(0);
}
}

if(f.equals(bt4))//anterior
{
if(paso < 1)
{
this.mensaje(1);
}
else
{
paso--;
miTabla.seek(miTabla.getList(0)[paso], 0);
this.verInfo();
}
}

if(f.equals(bt5))//siguiente
{
if(paso < (miTabla.getList(0).length-1))
{
if(paso == 0)
{
miTabla.seek(miTabla.getList(0)[0], 0);
this.verInfo();
}

paso++;
miTabla.seek(miTabla.getList(0)[paso], 0);
this.verInfo();
}
else
{
this.mensaje(1);
}
}

if(f.equals(bt6))//ultimo
{
if(miTabla.getList(0).length > 0)
{
paso = (miTabla.getList(0).length-1);
miTabla.seek(miTabla.getList(0)[paso], 0);
this.verInfo();
}
else
{
this.mensaje(0);
}
}

mdlt.setDataVector(miTabla.getTable(), cols);
lista.setListData(miTabla.getList(0));
}

public static void main(String[] args)
{
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);

new Ventana();
}

}
Datos archivados del Taringa! original
16puntos
0visitas
0comentarios
Actividad nueva en Posteamelo
0puntos
11visitas
0comentarios
Dar puntos:

Dejá tu comentario

0/2000

Autor del Post

e
edwin888🇦🇷
Usuario
Puntos0
Posts1
Ver perfil →
PosteameloArchivo Histórico de Taringa! (2004-2017). Preservando la inteligencia colectiva de la internet hispanohablante.

CONTACTO

18 de Septiembre 455, Casilla 52

Chillán, Región de Ñuble, Chile

Solo correo postal

© 2026 Posteamelo.com. No afiliado con Taringa! ni sus sucesores.

Contenido preservado con fines históricos y culturales.