import java.io.*;
class Esquema
{
String atributo[] = new String[20];
String tipo[] = new String[20];
int longitud[] = new int[20];
int decimal[] = new int[20];
int posicion[] = new int[20];
String contenido[] = new String[20];
int ultimo ;
Esquema(String _nombreTabla)
{
boolean hayDatos = true;
int acumulado ;
String area ;
try
{
BufferedReader entrada =
new BufferedReader(new FileReader(_nombreTabla + ".def"));
ultimo = 0;
acumulado = 0;
while( hayDatos )
{
area = entrada.readLine();
if( area == null )
hayDatos = false;
else
{
atributo[ultimo] = area;
tipo[ultimo] = entrada.readLine();
area = entrada.readLine();
longitud[ultimo] = Integer.parseInt(area);
area = entrada.readLine();
if( area == null )
decimal[ultimo] = 0;
else
decimal[ultimo] = Integer.parseInt(area);
posicion[ultimo] = acumulado;
acumulado += longitud[ultimo];
ultimo++;
}
}
entrada.close();
}
catch(IOException e)
{}
}
/** DEVULVE EL INDICE DEL ULTIMO ATRIBUTO DE LA TABLA */
int daUltimo()
{
return ultimo;
}
/** DEVULVE EL TAMAÑO DE LA TUPLA EN BYTES */
int tamano()
{
int _tamano ;
_tamano = 0;
for(int i = 0; i < ultimo; i++ )
_tamano += longitud[i];
return _tamano;
}
/** INDICA EL INDICE DE UN ATRIBUTO EN BASE A SU NOMBRE*/
int daIndice(String _atributo)
{
int i ;
boolean esta ;
esta = false;
for( i = 0; (i < ultimo) && esta == false; i++ )
if( _atributo.equals(atributo[i]) )
esta = true;
if( esta )
return i;
else
return -1;
}
int daPosicion(int _indice)
{
return posicion[_indice];
}
int daLongitud(int _indice)
{
return longitud[_indice];
}
String daAtributo(int _indice)
{
return atributo[_indice];
}
String daTipo(int _indice)
{
return tipo[_indice];
}
int daDecimal(int _indice)
{
return decimal[_indice];
}
String daContenido(int _indice)
{
return contenido[_indice];
}
/** INICIALIZA LAS AREAS DE CONTENIDO CON NULOS */
void limpia()
{
for( int i = 0; i < ultimo; i++ )
contenido[i] = new String("");
}
/** GUARDA EL CONTENIDO DE UN ATRIBUTO */
void guarda(int _indice ,String _valor)
{
StringBuffer dato = new StringBuffer(longitud[_indice]);
int _longitud ;
//System.out.println("atributo " + _indice + " " + _valor);
if( _valor.length() > longitud[_indice] )
dato = new StringBuffer(_valor.substring(0 ,longitud[_indice]));
else
dato = new StringBuffer(_valor);
//System.out.println("/"+dato+"/");
for( _longitud = dato.length(); _longitud < longitud[_indice]; _longitud++ )
dato.append(" ");
//System.out.println("/"+dato+"/");
contenido[_indice] = new String(dato);
}
/** RECUPERA EL CONTENIDO DE UN ATRIBUTO */
String recupera(int _indice)
{
return contenido[_indice];
}
String daTupla()
{
StringBuffer tupla = new StringBuffer(250);
int i ;
for( i = 0; i < ultimo; i++ )
{
tupla.append(contenido[i]);
}
return tupla.toString();
}
void carga(String _registro)
{
for( int i = 0; i < ultimo; i++ )
{
contenido[i] = new String(_registro.substring(posicion[i] ,posicion[i] + longitud[i]));
// System.out.println("/" +contenido[i] + "/");
}
}
}
class Tabla extends Esquema
{
String nombreTabla ;
RandomAccessFile archivo = null;
Registro registro ;
Tabla(String _nombreTabla)
{
super(_nombreTabla);
nombreTabla = _nombreTabla;
try {
archivo = new RandomAccessFile(_nombreTabla + ".inf" ,"rw");
}catch(IOException e){}
}
void escribe(long _indice ,String _tupla)
{
try {
archivo.seek(_indice * super.tamano());
archivo.writeBytes(_tupla);
}catch(IOException e){}
}
String lee(long _indice)
{
byte arreglo[] = new byte[super.tamano()];
try
{
archivo.seek(_indice * super.tamano() );
archivo.read(arreglo); // ,0 ,super.tamano());
}
catch(IOException e)
{}
return new String(arreglo);
}
long ultimaTupla()
{
long registros = 0;
try
{
registros = archivo.length() / super.tamano();
}
catch(IOException e)
{}
return registros;
}
void cierra()
{
try
{
archivo.close();
}
catch(IOException e)
{}
}
}
class Smbd
{
public static void main(String args[]) throws IOException
{
BufferedReader consola = new BufferedReader(new InputStreamReader(System.in));
int opcion ,indice ,ultimo = 0;
Tabla tabla = null ;
// DESPLEGA UN INDICADOR PARA LEER UN DATO
opcion = 0;
while( opcion != 5 )
{
System.out.println("\n1. Abrir Tabla\n2. Lee Tupla i\n3. Escribe Tupla i\n4. Despliega Tabla\n5. Salir");
System.out.print("> ");
String cadena = consola.readLine();
try
{
opcion = Integer.parseInt(cadena);
}
catch(Exception e)
{
opcion = 0;
}
switch( opcion )
{
case 1:
System.out.print("tabla> ");
cadena = consola.readLine();
tabla = new Tabla(cadena);
ultimo = tabla.daUltimo();
for( indice = 0; indice < ultimo; indice++ )
{
System.out.println(tabla.daAtributo(indice) + " " +
tabla.daTipo(indice) + " " +
tabla.daLongitud(indice) + " " +
tabla.daDecimal(indice));
}
System.out.println("Hay " + tabla.ultimaTupla() + " registros");
break;
case 2:
System.out.print("\ntupla #> ");
cadena = consola.readLine();
String reg = tabla.lee(Integer.parseInt(cadena));
System.out.println("/"+ reg +"/");
tabla.carga(reg);
for( indice = 0; indice < ultimo; indice++ )
{
System.out.println(tabla.daAtributo(indice)+ " /"
+ tabla.daContenido(indice) +"/");
}
break;
case 3:
tabla.limpia();
for( indice = 0; indice < ultimo; indice++ )
{
System.out.print(tabla.daAtributo(indice)+ "> ");
cadena = consola.readLine();
tabla.guarda(indice ,cadena);
}
System.out.print("/"+ tabla.daTupla() + "/\ntupla #> ");
cadena = consola.readLine();
tabla.escribe(Integer.parseInt(cadena) ,tabla.daTupla());
break;
case 4:
long numReg ,ultimoReg ;
ultimoReg = tabla.ultimaTupla();
for( numReg = 0; numReg < ultimoReg; numReg++ )
{
reg = tabla.lee(numReg);
tabla.carga(reg);
System.out.println(numReg + " /"+ tabla.daTupla() + "/");
}
break;
case 5:
tabla.cierra();
break;
}
}
}
}
Diccionario de Datos /* Abc.java
ACTUALIZACION EN UNA TABLA
2003 07 Jesus Olivares
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class LeeRegistro extends JFrame
{
// PANEL AJUSTABLE PARA LA PANTALLA
JSplitPane panelAjustable = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
// ETIQUETAS DE LOS CAMPOS DE DATOS
JLabel eAtributo = new JLabel("Atributo:" );
JLabel eTipo = new JLabel("Tipo: ");
JLabel eLongitud = new JLabel("Longitud: ");
JLabel eDecimal = new JLabel("Decimal: ");
// CAMPOS DE DATOS
JTextField vAtributo = new JTextField(20);
JTextField vTipo = new JTextField(1);
JTextField vLongitud = new JTextField(3);
JTextField vDecimal = new JTextField(2);
// BOTONES DE ACTUALIZACION
JPanel panelBotones = new JPanel(new FlowLayout());
// OBJETO AL QUE SE LE AGREGA EL REGISTRO O EN EL QUE SE HACEN CAMBIOS
DefaultTableModel modelo ;
int renglon ;
boolean hacerCambio ;
JButton salir = new JButton("Cancelar");
ActionListener accionSalir = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dispose();
}
};
JButton aceptar = new JButton("Aceptar");
ActionListener accionAceptar = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if( hacerCambio )
{
modelo.setValueAt(vAtributo.getText(), renglon ,0);
modelo.setValueAt(vTipo.getText(), renglon ,1);
modelo.setValueAt(vLongitud.getText(), renglon ,2);
modelo.setValueAt(vDecimal.getText(), renglon ,3);
}
else
{
String info [] = new String[4];
info[0] = vAtributo.getText();
info[1] = vTipo.getText();
info[2] = vLongitud.getText();
info[3] = vDecimal.getText();
modelo.addRow(info);
}
dispose(); // CIERRA LA VENTANA
}
};
void construyeVentana()
{
Container cont = getContentPane();
Panel panel = new Panel(new GridLayout(5,2));
// ASIGNA LOS COMPONENTES EN EL PANEL DE BOTONES
panel.add(eAtributo);
panel.add(vAtributo);
panel.add(eTipo);
panel.add(vTipo);
panel.add(eLongitud);
panel.add(vLongitud);
panel.add(eDecimal);
panel.add(vDecimal);
panel.add(aceptar);
panel.add(salir);
cont.add(panel);
// ASIGNA LAS ACCIONES
aceptar.addActionListener(accionAceptar);
salir.addActionListener(accionSalir);
// ACCION PARA CUANDO SE PIDE EL CIERRE DE LA VENTANA
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
}
});
}
// CONSTRUCTOR PARA HACER ALTAS
public LeeRegistro(DefaultTableModel _modelo)
{
modelo = _modelo;
construyeVentana();
hacerCambio = false;
}
// CONSTRUCTOR PARA HACER CAMBIOS
public LeeRegistro(DefaultTableModel _modelo ,String []datos ,int _renglon)
{
modelo = _modelo;
construyeVentana();
renglon = _renglon;
// ASIGNA LOS COMPONENTES EN EL PANEL DE BOTONES
vAtributo.setText(datos[0]);
vTipo.setText(datos[1]);
vLongitud.setText(datos[2]);
vDecimal.setText(datos[3]);
hacerCambio = true;
}
}
class PantallaAbc extends JFrame
{
// PANEL AJUSTABLE PARA LA PANTALLA
JSplitPane panelAjustable = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
// DATOS DE LA TABLA
DefaultTableModel modelo = new DefaultTableModel(0,4);
JTable tabla = new JTable(modelo);
JScrollPane panelScroll = new JScrollPane(tabla);
JPanel marcoTabla = new JPanel(new GridLayout(1,1));
JTextField tablaNombre = new JTextField(15);
// BOTONES DE ACTUALIZACION
JButton alta = new JButton("ALTA");
ActionListener altaAccion = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
LeeRegistro nuevo = new LeeRegistro(modelo);
nuevo.setSize(300,200);
nuevo.show();
}
};
JButton baja = new JButton("BAJA");
ActionListener bajaAccion = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int ultimo ,seleccion ;
ultimo = tabla.getRowCount();
seleccion = tabla.getSelectedRow();
if( seleccion != -1 )
modelo.removeRow(seleccion);
}
};
JButton cambio = new JButton("CAMBIO");
ActionListener cambioAccion = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int seleccion ;
seleccion = tabla.getSelectedRow();
if( seleccion != -1 )
{
String [] datos = new String[4];
datos[0] = (String)modelo.getValueAt(seleccion ,0);
datos[1] = (String)modelo.getValueAt(seleccion ,1);
datos[2] = (String)modelo.getValueAt(seleccion ,2);
datos[3] = (String)modelo.getValueAt(seleccion ,3);
LeeRegistro nuevo = new LeeRegistro(modelo, datos ,seleccion);
nuevo.setSize(300,200);
nuevo.show();
}
}
};
JButton salir = new JButton("SALIR");
ActionListener salirAccion = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dispose();
}
};
JButton guarda = new JButton("GUARDA");
ActionListener guardaAccion = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String [] datos = new String[4];
int ultimo ,seleccion ;
try{
BufferedWriter salida =
new BufferedWriter(new FileWriter(tablaNombre.getText() + ".def" ,true));
ultimo = tabla.getRowCount();
for( seleccion = 0; seleccion < ultimo; seleccion++ )
{
datos[0] = (String)modelo.getValueAt(seleccion ,0);
datos[1] = (String)modelo.getValueAt(seleccion ,1);
datos[2] = (String)modelo.getValueAt(seleccion ,2);
datos[3] = (String)modelo.getValueAt(seleccion ,3);
// ESCRIBE EL RESULTADO DE LA SUMA EN EL ARCHIVO DE SALIDA
salida.write(datos[0] + "\n");
salida.write(datos[1] + "\n");
salida.write(datos[2] + "\n");
salida.write(datos[3] + "\n");
}
salida.close();
}catch(IOException evento){
System.out.println("HAY PROBLEMAS" + evento);
}
try
{
RandomAccessFile contenido = new RandomAccessFile(tablaNombre.getText() + ".inf" ,"rw");
contenido.close();
}
catch(IOException ex)
{}
System.out.println("tabla creada");
}
};
JButton carga = new JButton("CARGA");
ActionListener cargaAccion = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
}
};
// PANEL PARA COLOCAR LOS BOTONES
JPanel panelBotones = new JPanel(new FlowLayout());
// CONSTRUCTOR
public PantallaAbc()
{
Container cont = getContentPane();
// COLOCA LOS ENCABEZADOS DE LAS COLUMNAS EN LA TABLA
tabla.getColumnModel().getColumn(0).setHeaderValue("atributo");
tabla.getColumnModel().getColumn(1).setHeaderValue("tipo");
tabla.getColumnModel().getColumn(2).setHeaderValue("longitud");
tabla.getColumnModel().getColumn(3).setHeaderValue("decimal");
// LA SELECCION DE ELEMENTOS ES SIMPLE
tabla.setSelectionMode((int)ListSelectionModel.SINGLE_SELECTION);
// ASIGNA LA TABLA EN EL PANEL DE MARCO
panelScroll.setPreferredSize(new Dimension(400, 300));
panelScroll.setMinimumSize(new Dimension(300, 200));
marcoTabla.setBorder(BorderFactory.createTitledBorder("Tabla"));
marcoTabla.add(panelScroll);
// ASIGNA LOS BOTONES DE ACCION EN EL PANEL DE BOTONES
panelBotones.add(alta);
panelBotones.add(baja);
panelBotones.add(cambio);
panelBotones.add(guarda);
panelBotones.add(carga);
panelBotones.add(tablaNombre);
panelBotones.add(salir);
// COLOCA LOS PANELES EN LA PANTALLA
panelAjustable.add(marcoTabla);
panelAjustable.add(panelBotones);
// AGREGA EL panelAjustable EN EL PANEL PRINCIPAL CENTRADO
cont.setLayout(new BorderLayout());
cont.add(panelAjustable, BorderLayout.CENTER);
// ASIGNA LAS ACCIONES
alta.addActionListener(altaAccion);
salir.addActionListener(salirAccion);
baja.addActionListener(bajaAccion);
cambio.addActionListener(cambioAccion);
guarda.addActionListener(guardaAccion);
carga.addActionListener(cargaAccion);
// ACCION PARA CUANDO SE PIDE EL CIERRE DE LA VENTANA
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
}
});
}
}
class Abc
{
public static void main(String args[])
{
PantallaAbc captura = new PantallaAbc();
captura.setSize(400, 400);
captura.show();
}
}
|
© Jesús M. Olivares Ceja septiembre 2003 mail@jesusolivares.com México
No hay comentarios:
Publicar un comentario