package componenteTabla;
import componenteTabla.*;
import java.util.*;
import javax.swing.table.TableModel;
import javax.swing.event.TableModelEvent;
import componenteTabla.*;
import javax.swing.JOptionPane;
import javax.swing.JDialog;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;
import java.awt.event.*;
import java.io.*;
import javax.swing.SwingUtilities;
import java.awt.*;
import java.text.SimpleDateFormat;
public class TableSorter1 extends TableMap implements Serializable
{
private int indexes[];
private Object[] columnasColor = null;
private Vector sortingColumns = new Vector();
private boolean ascending = true;
private boolean enabledOrdenar = true;
private int compares;
private String[] tiposColumnas = null;
private int filacorriente = -1;
private boolean modificar;
private boolean insertar;
private boolean eliminar;
public boolean insertarModif = false;
private int rowAnt = 0;
private String[] listaColumnasOrdenarSorter = {"(ninguna)", "(ninguna)", "(ninguna)", "(ninguna)"};
private boolean[] ascendente = {true, true, true, true};
private Vector filaDelEventoDespues = null;
private Vector filaDelEventoAntes = null;
private Vector vectorFilaEliminada = new Vector();
private RowModel rowFilaEliminada = new RowModel();
private Vector vectorFilaModificada = new Vector();
private RowModel rowFilaModificada = new RowModel();
private int indiceDeBusqueda = -1;
private String[] tipoColumna;
private Object[] infoCombo = null;
private boolean confirmacion = false;
private boolean confirmarEliminacion = false;
private boolean confirmarInsercion = false;
private boolean confirmarModificacion = false;
compomenteABMCList componenteRef;
private int primaryKeyColumn = -1;
public TableSorter1()
{
indexes = new int[0]; // for consistency
tiposColumnas = null;
}
public TableSorter1(TableModel model, String[] tc, compomenteABMCList ref)
{
componenteRef = ref;
setModel(model);
tiposColumnas = tc;
}
public void setTiposColumnas(String[] tc)
{
Model model = (Model) getModel();
tiposColumnas = tc;
model.setTiposColumnas(tc);
setModel(model);
}
public void setListaColumnasOrdenarSorter(String[] lco)
{
listaColumnasOrdenarSorter = lco;
}
public void setAscendenteSorter(boolean[] a)
{
ascendente = a;
}
public void setDatos(Object[][] datos)
{
Model model = (Model) getModel();
model.setDatos(datos);
this.setModel(model);
}
public void setDatos(Object[][] datos, int cols)
{
Model model = (Model) getModel();
model.setDatos(datos, cols);
this.setModel(model);
}
public void setDatos(Vector rows)
{
Model model = (Model) getModel();
model.setDatos(rows);
this.setModel(model);
}
public void setDatos(RowModelCollection rows)
{
Model model = (Model) getModel();
model.setDatos(rows);
this.setModel(model);
}
public Vector getVectorFila()
{
return vectorFilaEliminada;
}
public RowModel getRowEliminada()
{
return rowFilaEliminada;
}
public int getIndiceDeBusqueda()
{
return indiceDeBusqueda;
}
public void setModel(TableModel model)
{
super.setModel(model);
reallocateIndexes();
}
public boolean[] getAscendente()
{
return ascendente;
}
public String[] getListaColumnasOrdenar()
{
return listaColumnasOrdenarSorter;
}
public Color getRowColor(int row)
{
Model modelo = (Model) getModel();
//int ultCol=modelo.getColumns()-1;
try
{
//return (Color)modelo.getValueAt(indexes[row],ultCol);
//return (Color)rowColors.get(new Integer(indexes[row]));
return modelo.getRowData().getRowAt(indexes[row]).getColor();
}
catch (Exception e2)
{
return Color.black;
}
}
public int getColumna(String str)
{
Model model = (Model) getModel();
if (str.equals("(ninguna)"))
return (-1);
for (int i = 0; i < model.getColumnCount(); i++)
if (this.getColumnName(i).equals(str))
return i;
return (-1);
}
public void setEnabledOrdenar(boolean b)
{
this.enabledOrdenar = b;
}
public void ordenar()
{
int col;
for (int i = 3; i >= 0; i--)
{
col = getColumna(listaColumnasOrdenarSorter[i]);
if (col != -1)
sortByColumn(col, ascendente[i]);
}
this.indiceDeBusqueda = getColumna(listaColumnasOrdenarSorter[0]);
}
public void setFilaCorriente(int fc)
{
filacorriente = fc;
Model model = (Model) getModel();
model.setFilaCorriente(filacorriente);
}
public String getEdicionTabla()
{
return ((Model) getModel()).getEdicion();
}
public void setEdicionInsertar(boolean b)
{
insertar = b;
}
public void setEdicionModificar(boolean b)
{
modificar = b;
}
public void setEdicionEliminar(boolean b)
{
eliminar = b;
}
public int compareRowsByColumn(int row1, int row2, int column)
{
Class type = model.getColumnClass(column);
TableModel data = model;
// Check for nulls.
Object o1 = data.getValueAt(row1, column);
Object o2 = data.getValueAt(row2, column);
// If both values are null, return 0.
if (o1 == null && o2 == null)
{
return 0;
}
else if (o1 == null)
{ // Define null less than everything.
return -1;
}
else if (o2 == null)
{
return 1;
}
/*
* We copy all returned values from the getValue call in case
* an optimised model is reusing one object to return many
* values. The Number subclasses in the JDK are immutable and
* so will not be used in this way but other subclasses of
* Number might want to do this to save space and avoid
* unnecessary heap allocation.
*/
if (type.getSuperclass() == java.lang.Number.class)
{
Number n1 = (Number) data.getValueAt(row1, column);
double d1 = n1.doubleValue();
Number n2 = (Number) data.getValueAt(row2, column);
double d2 = n2.doubleValue();
if (d1 < d2)
{
return -1;
}
else if (d1 > d2)
{
return 1;
}
else
{
return 0;
}
}
else if (type == java.util.Date.class || type == java.sql.Timestamp.class || type == java.sql.Date.class)
{
Date d1 = (Date) data.getValueAt(row1, column);
long n1 = d1.getTime();
Date d2 = (Date) data.getValueAt(row2, column);
long n2 = d2.getTime();
if (n1 < n2)
{
return -1;
}
else if (n1 > n2)
{
return 1;
}
else
{
return 0;
}
}
else if (type == String.class)
{
String s1 = (String) data.getValueAt(row1, column);
String s2 = (String) data.getValueAt(row2, column);
try{
SimpleDateFormat s = new SimpleDateFormat("d-M-yyyy");
if(s1.lastIndexOf(":")!=-1 )
s = new SimpleDateFormat("d-M-yyyy");
Date d1 = s.parse(s1) ;
Date d2 = s.parse(s2) ;
long n1 = d1.getTime();
long n2 = d2.getTime();
if (n1 < n2) return -1;
else if (n1 > n2) return 1;
else return 0;
}
catch (Exception ex){
//--si no es date lo veo como texto ------------
int result = s1.compareTo(s2);
if (result < 0){
return -1;
}
else if (result > 0){
return 1;
}
else{
return 0;
}
}
}
else if (type == Boolean.class)
{
Boolean bool1 = (Boolean) data.getValueAt(row1, column);
boolean b1 = bool1.booleanValue();
Boolean bool2 = (Boolean) data.getValueAt(row2, column);
boolean b2 = bool2.booleanValue();
if (b1 == b2)
{
return 0;
} //como esta ordena primero los true
else if (b2) //else if (b1)
{ // Define false < true
return 1;
}
else
{
return -1;
}
}
else
{
Object v1 = data.getValueAt(row1, column);
String s1 = v1.toString();
Object v2 = data.getValueAt(row2, column);
String s2 = v2.toString();
int result = s1.compareTo(s2);
if (result < 0)
{
return -1;
}
else if (result > 0)
{
return 1;
}
else
{
return 0;
}
}
}
public int compare(int row1, int row2)
{
compares++;
for (int level = 0; level < sortingColumns.size(); level++)
{
Integer column = (Integer) sortingColumns.elementAt(level);
int result = compareRowsByColumn(row1, row2, column.intValue());
if (result != 0)
{
return ascending ? result : -result;
}
}
return 0;
}
public void reallocateIndexes()
{
int rowCount = model.getRowCount();
// Set up a new array of indexes with the right number of elements
// for the new data model.
indexes = new int[rowCount];
// Initialise with the identity mapping.
for (int row = 0; row < rowCount; row++)
{
indexes[row] = row;
}
}
public void checkModel()
{
if (indexes.length != model.getRowCount())
{
System.err.println("Cambios en el modelo no registrados.");
}
}
public void sort(Object sender)
{
checkModel();
compares = 0;
shuttlesort((int[]) indexes.clone(), indexes, 0, indexes.length);
}
public void n2sort()
{
for (int i = 0; i < getRowCount(); i++)
{
for (int j = i + 1; j < getRowCount(); j++)
{
if (compare(indexes[i], indexes[j]) == -1)
{
swap(i, j);
}
}
}
}
// This is a home-grown implementation which we have not had time
// to research - it may perform poorly in some circumstances. It
// requires twice the space of an in-place algorithm and makes
// NlogN assigments shuttling the values between the two
// arrays. The number of compares appears to vary between N-1 and
// NlogN depending on the initial order but the main reason for
// using it here is that, unlike qsort, it is stable.
public void shuttlesort(int from[], int to[], int low, int high)
{
if (high - low < 2)
{
return;
}
int middle = (low + high) / 2;
shuttlesort(to, from, low, middle);
shuttlesort(to, from, middle, high);
int p = low;
int q = middle;
/* This is an optional short-cut; at each recursive call,
check to see if the elements in this subset are already
ordered. If so, no further comparisons are needed; the
sub-array can just be copied. The array must be copied rather
than assigned otherwise sister calls in the recursion might
get out of sinc. When the number of elements is three they
are partitioned so that the first set, [low, mid), has one
element and and the second, [mid, high), has two. We skip the
optimisation when the number of elements is three or less as
the first compare in the normal merge will produce the same
sequence of steps. This optimisation seems to be worthwhile
for partially ordered lists but some analysis is needed to
find out how the performance drops to Nlog(N) as the initial
order diminishes - it may drop very quickly. */
if (high - low >= 4 && compare(from[middle - 1], from[middle]) <= 0)
{
for (int i = low; i < high; i++)
{
to[i] = from[i];
}
return;
}
// A normal merge.
for (int i = low; i < high; i++)
{
if (q >= high || (p < middle && compare(from[p], from[q]) <= 0))
{
to[i] = from[p++];
}
else
{
to[i] = from[q++];
}
}
}
public void swap(int i, int j)
{
int tmp = indexes[i];
indexes[i] = indexes[j];
indexes[j] = tmp;
}
// The mapping only affects the contents of the data rows.
// Pass all requests to these rows through the mapping array: "indexes".
public Object getValueAt(int aRow, int aColumn)
{
Model model = (Model) getModel();
checkModel();
try
{
return model.getValueAt(indexes[aRow], aColumn);
}
catch (Exception ex)
{
return new Object();
}
}
public void setValueAt(Object aValue, int aRow, int aColumn)
{
Model model = (Model) getModel();
checkModel();
model.setValueAt(aValue, indexes[aRow], aColumn);
}
public void sortByColumn(int column)
{
sortByColumn(column, true);
}
public void actualizarOrdenamiento(int column)
{
Model model = (Model) getModel();
String s, s1;
boolean b = true, b1;
int i;
s = listaColumnasOrdenarSorter[0];
listaColumnasOrdenarSorter[0] = (model.getColumnNames())[column];
s1 = listaColumnasOrdenarSorter[1];
listaColumnasOrdenarSorter[1] = s;
s = listaColumnasOrdenarSorter[2];
listaColumnasOrdenarSorter[2] = s1;
listaColumnasOrdenarSorter[3] = s;
b = ascendente[0];
ascendente[0] = true;
b1 = ascendente[1];
ascendente[1] = b;
b = ascendente[2];
ascendente[2] = b1;
ascendente[3] = b;
indiceDeBusqueda = getColumna(listaColumnasOrdenarSorter[0]);
}
public void sortByColumn(int column, boolean ascending)
{
this.ascending = ascending;
sortingColumns.removeAllElements();
sortingColumns.addElement(new Integer(column));
sort(this);
super.tableChanged(new TableModelEvent(this));
}
// There is no-where else to put this.
// Add a mouse listener to the Table to trigger a table sort
// when a column heading is clicked in the JTable.
public boolean isEnabledOrdenar()
{
return enabledOrdenar;
}
public void setIndiceDeBusqueda(int ind)
{
indiceDeBusqueda = ind;
}
public void addMouseListenerToHeaderInTable(JTable table)
{
final TableSorter1 sorter = this;
Model model = (Model) getModel();
final JTable tableView = table;
tableView.setColumnSelectionAllowed(false);
MouseAdapter listMouseListener = new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
if (isEnabledOrdenar())
{
TableColumnModel columnModel = tableView.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = tableView.convertColumnIndexToModel(viewColumn);
if (e.getClickCount() == 1 && column != -1)
{
int shiftPressed = e.getModifiers() & InputEvent.SHIFT_MASK;
boolean ascending = (shiftPressed == 0);
sorter.sortByColumn(column, ascending);
setIndiceDeBusqueda(column);
actualizarOrdenamiento(column);
indiceDeBusqueda = column;
} // actualizarOrdenamiento(column);
}
}
};
JTableHeader th = tableView.getTableHeader();
th.addMouseListener(listMouseListener);
//
table.repaint();
}
public int getColumnaOrdenamiento()
{
return this.indiceDeBusqueda;
}
/************************************************************************/
/************************************************************************/
public int BusquedaRapida(Object dato, int column)
{
Class type = model.getColumnClass(column);
TableModel data = model;
int row = 0;//numero de fila
// Check for nulls.
if (data.getRowCount() == 0)
{
return row;
}
Object v1 = dato;
String s1 = null;
if (v1 != null)
{
s1 = v1.toString();
s1 = s1.toUpperCase();
if (s1.length() == 0 || s1.length() == 1)//primera Busqueda
rowAnt = 0;
}
for (row = 0; row < data.getRowCount(); row++)
{
Object v2 = data.getValueAt(indexes[row], column);
if (v2 != null && s1 != null)
{
String s2 = v2.toString();
s2 = s2.toUpperCase();
if (s2.startsWith(s1, 0))
{
rowAnt = row;
return row;
}
}
}//for
return -1;
}
public void posicionAlComienzo(int row, JTable table, int scrollHeight)
{
JTable tableView = table;
TableModel data = model;
Dimension size = new Dimension(0, 0);
int rowTotal = data.getRowCount() - 1;
int rowMargen = tableView.getRowMargin();
int rowHeight = tableView.getRowHeight() + rowMargen;
int tableWidth = tableView.getWidth();
int tableHeight = tableView.getHeight();
size.width = 0;
size.height = (rowTotal * rowHeight) + scrollHeight;//
// para poder desplazar la ultima fila a la altura del Header
tableView.setPreferredSize(size);
tableView.revalidate();
Rectangle rectRes = new Rectangle(0, 0, 0, 0);//reset
tableView.scrollRectToVisible(rectRes);
Rectangle rect = new Rectangle(0, row * rowHeight, tableWidth, tableHeight * 2);
tableView.scrollRectToVisible(rect);
/*int y = getViewport().getViewPosition().y;
y += getViewport().getExtentSize().getHeight();
int row = table.rowAtPoint(new Point(0,y));
return (row > -1) ? row : (
table.getRowCount() - 1); */
}
public void setOidAt(Object value, int row, int col)
{
Model model = (Model) getModel();
model.setOidAt(value, indexes[row], col);
}
public void setRowColor(Color c, int row)
{
Model model = (Model) getModel();
//model.setColorAt(c,indexes[row],model.getColumns()-1);
//this.setModel(model);
model.getRowData().getRowAt(indexes[row]).setColor(c);
//rowColors.put(new Integer(row),c);
}
public Object[] getColumnasColor()
{
return columnasColor;
}
public void setColumnasColor(Object[] columnas)
{
columnasColor = columnas;
}
// Genera valores iniciales para cada tipo.
// Utilizado en la insercion.
public Object getDafaultValue(int column)
{
try
{
Object com[] = (Object[]) infoCombo[column];
if (com != null && com[0] != null)
return com[0];
if (tiposColumnas[column].equals("String"))
return new String("");
else
if (tiposColumnas[column].equals("Float"))
return new Float(0.0);
else
if (tiposColumnas[column].equals("Integer"))
return new Integer(0);
else
if (tiposColumnas[column].equals("Double"))
return new Double(0.0);
else
if (tiposColumnas[column].equals("Boolean"))
return new Boolean(false);
else
if (tiposColumnas[column].equals("Date"))
return new Date();
else
if (tiposColumnas[column].equals("Long"))
return new Long("0");
else
if (tiposColumnas[column].equals("Short"))
return new Short("0");
else
if (tiposColumnas[column].equals("BigInteger"))
return new java.math.BigInteger("0");
else
if (tiposColumnas[column].equals("Color"))
return new Color(0, 0, 0);
else
if (tiposColumnas[column].equals("AbmLista"))
return null;
}
catch (Exception e)
{
return new Integer(0);
}
return null;
}
public Object[] eliminarFila(int fila)
{
Model model = (Model) getModel();
int filaaeliminar = fila;
int cols = model.getColumns();
Object[] filaEliminada = new Object[cols];
int result = 0;
int col = model.getColumns();
int filas = model.getRowCount();
if (filas != 0)
{
if (filas == 1)
{
/*Object[][] dataAux = new Object[0][0];
for (int g = 0; g < col; g++)
filaEliminada[g] = getValueAt(filaaeliminar, g);
model.setDatos(dataAux, col);*/
rowFilaEliminada = (RowModel) model.getRowData().getRowAt(0).clone();
filaEliminada = rowFilaEliminada.getValues().toArray();
model.removeDatosAt(0);
this.setModel(model);
this.fireTableDataChanged();
}
if (filas > 1)
{
try
{
rowFilaEliminada = (RowModel) model.getRowData().getRowAt(indexes[filaaeliminar]).clone();
filaEliminada = rowFilaEliminada.getValues().toArray();
model.removeDatosAt(indexes[filaaeliminar]);
this.setModel(model);
this.fireTableDataChanged();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
return filaEliminada;
}
public int eliminarFila()
{
Model model = (Model) getModel();
int filaaeliminar = filacorriente;
int result = 0;
// controla si hay fila seleccionada para eliminar
if (filaaeliminar == -1)
{
JOptionPane pane = new JOptionPane();
Object[] options = { "Aceptar" };
pane.setOptions(options);
pane.setOptionType(0);
pane.setMessage("Debe seleccionar una fila para eliminar");
pane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = pane.createDialog(componenteRef.getParentFrame(), "Eliminar Elemento");
result = -2;
dialog.setModal(true);
dialog.show();
}
else
{/*** ventana de confirmacion *****/
if (confirmacion && isConfirmarEliminacion())
{
JOptionPane pane = new JOptionPane();
Object[] options = { "Si", "No" };
pane.setOptions(options);
pane.setOptionType(0);
pane.setMessage("Confirma que desea Eliminar el elemento seleccionado? ");
pane.setMessageType(JOptionPane.QUESTION_MESSAGE);
JDialog dialog = pane.createDialog(componenteRef.getParentFrame(), "Eliminar Elemento");
dialog.setModal(true);
dialog.show();
Object selectedValue = pane.getValue(); // no
if (selectedValue.equals(null) || options[1].equals(selectedValue))
result = 1;
}
else
result = 0;
vectorFilaEliminada.removeAllElements();
rowFilaEliminada = (RowModel) model.getRowData().getRowAt(indexes[filaaeliminar]).clone();
for (int f = 0; f < model.getColumns(); f++)
vectorFilaEliminada.addElement(getValueAt(filaaeliminar, f));
/*int col = model.getColumns();
int fila = model.getRowCount();
Object[][] dataAux = new Object[fila - 1][col];
if (result == 0)
{
for (int i = 0; i < fila; i++)
for (int j = 0; j < col; j++)
if (i < filaaeliminar)
dataAux[i][j] = getValueAt(i, j);
else
if (i > filaaeliminar)
dataAux[i - 1][j] = getValueAt(i, j);
model.setValues(model.getColumnNames(), dataAux);
this.setModel(model);
this.fireTableDataChanged();
}*/
if (result == 0)
{
model.removeDatosAt(indexes[filaaeliminar]);
this.setModel(model);
this.fireTableDataChanged();
}
}
return result;
}
//
public int insertarFilaConConfirmacion(Object[] datos)
{
Model model = (Model) getModel();
int filaainsertar = model.getRowCount() - 1;
int result = filaainsertar;
int colVisibles = model.getColumnCount();//retorna la cantidad de columnas visibles en la tabla
int colReales = model.getColumns();//retorna la cantidad de columnas, incluyendo las no visibles
int fila = model.getRowCount();
int longDatos;
//Object[][] dataAux = new Object[fila + 1][colReales];
Object[] dataAux = new Object[colReales];
if (datos != null)
longDatos = datos.length;
else
longDatos = 0;
for (int j = 0; j < colReales; j++)
{
try
{
if (j < longDatos)
{
if (datos[j] != null)
dataAux[j] = datos[j];
else
dataAux[j] = getDafaultValue(j);
}
else
if (j < colVisibles)
dataAux[j] = getDafaultValue(j);
else
dataAux[j] = new Integer(0);
}
catch (Exception g)
{
g.printStackTrace();
}
}
/*if (datos != null)
longDatos = datos.length;
else longDatos = 0;
// controla si hay fila seleccionada para insertar
if (filaainsertar == -1) //es la primera insercion
{
if (fila == 0)
{
for (int j = 0; j < colReales; j++)
{
try
{
if (j < longDatos)
{
if (datos[j] != null)
dataAux[0][j] = datos[j];
else
dataAux[0][j] = getDafaultValue(j);
}
else
if (j < colVisibles)
dataAux[0][j] = getDafaultValue(j);
else
dataAux[0][j] = new Integer(0);
}
catch (Exception g)
{
g.printStackTrace();
}
}
// model.setValues(model.getColumnNames(),dataAux);
model.setDatos(dataAux, this.getColumnCount());
this.setModel(model);
model.setEdicion("Insertar");
this.insertarModif = true;
this.fireTableDataChanged();
}
}
if (result != -1)
{
for (int i = 0; i <= fila; i++)
for (int j = 0; j < colReales; j++)
{
if (i == fila)
{
if (j < longDatos)
{
if (datos[j] != null)
dataAux[i][j] = datos[j];
else
dataAux[i][j] = getDafaultValue(j);
}
else
{
if (j < colVisibles)
{
dataAux[i][j] = getDafaultValue(j);
}
else
{
dataAux[i][j] = new Integer(0);
}
}
}
else
{
dataAux[i][j] = model.getValueAt(i, j);
}
}
}
model.setValues(model.getColumnNames(), dataAux);*/
model.addDatos(dataAux);
/*int auxArray[] = new int[indexes.length + 1];
System.arraycopy(indexes, 0, auxArray, 0, indexes.length);
indexes = auxArray;
for (int i=indexes.length-1;i>fila;--i)
indexes[i] = indexes[i-1]+1;
indexes[fila] = fila;*/
this.setModel(model);
model.setEdicion("Insertar");
this.insertarModif = true;
this.fireTableDataChanged();
return filaainsertar;
}
public int insertarFila(Object[] datos)
{
Model model = (Model) getModel();
int filaainsertar = model.getRowCount() - 1;
/*int result=filaainsertar;
int colVisibles=model.getColumnCount();//retorna la cantidad de columnas visibles en la tabla
int colReales=model.getColumns();//retorna la cantidad de columnas, incluyendo las no visibles
int fila=model.getRowCount();
int longDatos;
//Object[][] dataAux=new Object[fila+1][colReales];
Object[] dataAux=new Object[colReales];
for(int j=0;j<colReales;j++)
{
if(datos[j]!=null)
dataAux[0][j]=datos[j];
else
dataAux[0][j]=getDafaultValue(j);
}*/
/*if (datos!=null)
longDatos=datos.length;
else longDatos=0;
// controla si hay fila seleccionada para insertar
if (filaainsertar==-1) //es la primera insercion
{ if(fila==0)
{
for(int j=0;j<colReales;j++)
{
try
{
if(j<longDatos)
{
if(datos[j]!=null)
dataAux[0][j]=datos[j];
else
dataAux[0][j]=getDafaultValue(j);
}
else
if(j<colVisibles)
dataAux[0][j]=getDafaultValue(j);
else
dataAux[0][j]=new Integer(0);
}
catch (Exception g)
{
g.printStackTrace();
}
}
// model.setValues(model.getColumnNames(),dataAux);
model.setDatos(dataAux,this.getColumnCount());
// model.setEdicion("Insertar");
this.fireTableDataChanged();
}
}
if (result!=-1)
{
for(int i=0;i<=fila;i++)
for(int j=0;j<colReales;j++)
{
if (i==fila)
{
if(j<longDatos)
{
if(datos[j]!=null)
dataAux[i][j]=datos[j];
else
dataAux[i][j]=getDafaultValue(j);
}
else
{ if(j<colVisibles)
{
dataAux[i][j]=getDafaultValue(j);
}
else
{
dataAux[i][j]=new Integer(0);
}
}
}
else
{
dataAux[i][j]=model.getValueAt(i,j);
}
}
}
model.setValues(model.getColumnNames(),dataAux);*/
model.addDatos(datos);
int auxArray[] = new int[indexes.length + 1];
System.arraycopy(indexes, 0, auxArray, 0, indexes.length);
indexes = auxArray;
indexes[indexes.length - 1] = indexes.length - 1;
//this.setModel(model);
//model.setEdicion("Insertar");
this.fireTableDataChanged();
return filaainsertar;
}
public int insertarFila()
{
Model model = (Model) getModel();
int filaainsertar = filacorriente;
int result = filaainsertar;
Integer selectedValue = new Integer(0);;
int valor = 0;
int colVisibles = model.getColumnCount();//retorna la cantidad de columnas visibles en la tabla
int colReales = model.getColumns();//retorna la cantidad de columnas, incluyendo las no visibles
int fila = model.getRowCount();
Object[] dataAux = new Object[colReales];
for (int j = 0; j < colReales; j++)
{
if (j < colVisibles)
dataAux[j] = getDafaultValue(j);
else
dataAux[j] = new Integer(0);//para setear los posibles oid de la fila
}
// controla si hay fila seleccionada para insertar
if (filaainsertar == -1) //es la primera insercion
{
if (fila == 0)
{
model.addDatos(dataAux);
this.setModel(model);
model.setEdicion("Insertar");
this.fireTableDataChanged();
}
else//no hay una fila seleccionada pero la tabla tiene mas de una fila
{
model.addDatos(dataAux);
this.setModel(model);
model.setEdicion("Insertar");
this.fireTableDataChanged();
valor = -2;
}
}
/**********/
if (result != -1)
{
model.insertDatosAt(dataAux, filaainsertar);
this.setModel(model);
this.fireTableDataChanged();
model.setEdicion("Insertar");
}
if (valor != -2)
return filaainsertar;
else
return valor;
}
public void insertarDatosFila(Object[] datosFila)//inserta una fila al final con los datos del vector
{
Model model = (Model) getModel();
int col = model.getColumnCount();
int fila = model.getRowCount() + 1;
Object[] dataAux = new Object[col];
for (int j = 0; j < col; j++)
dataAux[j] = datosFila[j];
if (fila == 0)
{
model.addDatos(dataAux);
this.setModel(model);
this.fireTableDataChanged();
model.setEdicion("Insertar");
}
else
{
model.addDatos(dataAux);
this.setModel(model);
this.fireTableDataChanged();
model.setEdicion("Insertar");
}
}
//
public void undo()
{
Model model = (Model) getModel();
model.recuperarDatos();
this.setModel(model);
this.fireTableDataChanged();
}
public void agregarColumnaOid(Object[] oids)
{
Model model = (Model) getModel();
int col = model.getColumns();
int fila = model.getRowCount();
Object[][] dataAux = new Object[fila][col];
{
for (int i = 0; i < fila; i++)
for (int j = 0; j < col; j++)
{
if (j == col - 1)
{
dataAux[i][j] = oids[i];
}
else
{
dataAux[i][j] = model.getValueAt(i, j);
}
}
}
model.setValues(model.getColumnNames(), dataAux);
for (int i = 0; i < model.getRowData().getRowCount() && i < oids.length; ++i)
model.getRowData().getRowAt(indexes[i]).setId(oids[i]);
this.setModel(model);
this.fireTableDataChanged();
}
public void cancelarEscape()
{
Model model = (Model) getModel();
model.recuperarDatos();
this.setModel(model);
this.ordenar();
this.fireTableDataChanged();
model.setEdicion("Default");
}
public int modificarFila(Object[] datos)
{
Model model = (Model) getModel();
int col = model.getColumns();
int filas = model.getRowCount();
Object[] dataAux = new Object[col];
for (int j = 0; j < col; j++)
dataAux[j] = datos[j];
model.setDatosAt(dataAux, indexes[filacorriente]);
this.setModel(model);
this.fireTableDataChanged();
return filacorriente;
}
public int modificarFila()
{
Model model = (Model) getModel();
int filaamodificar = filacorriente;
model.setFilaCorriente(filacorriente);
if (filaamodificar == -1)
{
JOptionPane pane = new JOptionPane();
Object[] options = { "Aceptar" };
pane.setOptions(options);
pane.setOptionType(0);
pane.setMessage("Debe seleccionar una fila para modificar");
pane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = pane.createDialog(componenteRef.getParentFrame(), "Modificar Elemento");
dialog.setModal(true);
dialog.show();
}
else
model.setEdicion("Modificar");
return filaamodificar;
}
public int updateFila(boolean insert)
{
Model model = (Model) getModel();
int result = 1;
Object selectedValue = null;
if ((confirmacion && isConfirmarModificacion() && !insert) || (confirmacion && isConfirmarInsercion() && insert))
{
JOptionPane pane = new JOptionPane();
Object[] options = { "Si", "No" };
pane.setOptions(options);
pane.setOptionType(0);
if (!insert)
pane.setMessage("Confirma que desea Actualizar los cambios ?. ");
else
pane.setMessage("Seguro desea insertar el elemento?. ");
pane.setMessageType(JOptionPane.QUESTION_MESSAGE);
JDialog dialog = pane.createDialog(componenteRef.getParentFrame(), "Confirmaci�n");
dialog.setModal(true);
dialog.show();
selectedValue = pane.getValue(); // no
for (int counter = 0, maxCounter = options.length;
counter < maxCounter; counter++)
if (options[counter].equals(selectedValue))
result = counter;
}
else
result = 0;
if (getPrimaryKeyColumn()>-1)
{
Object key = this.getValueAt(filacorriente, getPrimaryKeyColumn());
for (int i=0;i<model.getRowDataOld().getRowCount();++i)
{
if(key instanceof java.lang.String){
if ( (insert || indexes[filacorriente] != i) &&
((String)key).equalsIgnoreCase((String)model.getRowDataOld().getRowAt(i).getValueAt(
getPrimaryKeyColumn()))){
JOptionPane.showMessageDialog(componenteRef.getParentFrame(),
"Ya se encuentra cargado un registro con ese ID");
result = 1;
break;
}
}
else
if ( (insert || indexes[filacorriente]!=i) && key.equals(model.getRowDataOld().getRowAt(i).getValueAt(getPrimaryKeyColumn())))
{
JOptionPane.showMessageDialog(componenteRef.getParentFrame(),
"Ya se encuentra cargado un registro con ese ID");
result = 1;
break;
}
}
}
if (result == 0) // modificar
{ //if(filacorriente!=-1)
loadRow(filacorriente, 1);
//ordenar();
model.setEdicion("Default");
this.fireTableDataChanged();
return 0;
}
if (result == 1) // cancelar
{
model.recuperarDatos();
int rows = model.getRowCount();
this.setModel(model);
model.setEdicion("Default");
this.fireTableDataChanged();
this.fireTableDataChanged();
return 1;
}
return result;
}
public void dispararCambioFila(int fila)
{
Model model = (Model) getModel();
if (fila >= 0 && indexes.length>=fila)
model.dispararCambioFila(indexes[fila]);
else
model.dispararCambioFila(-2);
}
public void setFilaSeleccionada(int fila)
{
if (fila > -1)
{
Model model = (Model) getModel();
//model.setFilaSeleccionada(indexes[fila]);
model.setFilaSeleccionada(fila);
}
}
public int updateFilaCero()
{
Model model = (Model) getModel();
int result = 1;
loadRow(filacorriente, 1);
ordenar();
model.setEdicion("Default");
this.fireTableDataChanged();
return 0;
}
//
public Vector getRowAntes()
{
return filaDelEventoAntes;
}
public Vector getRowDespues()
{
return filaDelEventoDespues;
}
public void setTipoColumna(String[] tc)
{
tipoColumna = tc;
}
public int obtenerIndiceCombo(Object s, int i)
{
if (infoCombo[i] == null)
return -1;
for (int j = 0; j < ((String[]) infoCombo[i]).length; j++)
{
if (((Object[]) infoCombo[i])[j] == null)
return -1;
if (s == null)
return -1;
if (((Object) ((Object[]) infoCombo[i])[j]).toString().compareTo(s.toString()) == 0)
return j;
}
return -1;
}
//devuelve un vector conteniendo los datos de una fila
public Vector getRow(int row)
{
int i = 0;
Vector V = new Vector();
for (i = 0; i < model.getColumnCount(); i++)
{
if (tipoColumna[i].equals("COMUN"))
V.addElement(getValueAt(row, i));
else if (tipoColumna[i].equals("ABMLISTA"))
V.addElement(getValueAt(row, i));
else
V.addElement(new Integer(obtenerIndiceCombo((Object) getValueAt(row, i), i)));
}
return V;
}
public void loadRow(int row, int old)
{
int i = 0;
Vector V = new Vector();
Model model = (Model) getModel();
// for (i=0;i<model.getColumnCount();i++)
for (i = 0; i < model.getColumnCount(); i++)
{
if (tipoColumna[i].equals("COMUN"))
V.addElement(getValueAt(row, i));
else if (tipoColumna[i].equals("ABMLISTA"))
V.addElement(getValueAt(row, i));
else if (tipoColumna[i].equals("DATE"))
V.addElement(getValueAt(row, i));
else
V.addElement(new Integer(obtenerIndiceCombo((Object) getValueAt(row, i), i)));
}
V.addElement(getValueAt(row, i));
if (old == 0) // antes de la modificacion (0)
filaDelEventoAntes = V;
else // despues de la modificacion (1)
filaDelEventoDespues = V;
}
public Vector getVectorFilaModificacion()
{
return vectorFilaModificada;
}
public RowModel getRowModificado()
{
return rowFilaModificada;
}
public void setVectorModificacion(int filaAnt)
{
Model model = (Model) getModel();
vectorFilaModificada.removeAllElements();
for (int f = 0; f < model.getColumns(); f++)
{
vectorFilaModificada.addElement(getValueAt(filaAnt, f));
}
rowFilaModificada = (RowModel) model.getRowData().getRowAt(indexes[filaAnt]).clone();
}
public int getIndice(int row)
{
return indexes[row];
}
public int filaOriginal(int fo)
{
if (fo != 0)
return indexes[fo];
else
return 1;
}
public void setInfoCombo(Object[] ic)
{
infoCombo = ic;
}
void writeObject(ObjectOutputStream oos) throws IOException
{
oos.defaultWriteObject();
}
void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException
{
ois.defaultReadObject();
}
public void setConfirmacion(boolean confirmacion)
{
this.confirmacion = confirmacion;
}
public boolean isConfirmacion()
{
return confirmacion;
}
public void setConfirmarEliminacion(boolean confirmarEliminacion)
{
this.confirmarEliminacion = confirmarEliminacion;
}
public boolean isConfirmarEliminacion()
{
return confirmarEliminacion;
}
public void setConfirmarInsercion(boolean confirmarInsercion)
{
this.confirmarInsercion = confirmarInsercion;
}
public boolean isConfirmarInsercion()
{
return confirmarInsercion;
}
public void setConfirmarModificacion(boolean confirmarModificacion)
{
this.confirmarModificacion = confirmarModificacion;
}
public boolean isConfirmarModificacion()
{
return confirmarModificacion;
}
public void setPrimaryKeyColumn(int primaryKeyColumn) {
this.primaryKeyColumn = primaryKeyColumn;
}
public int getPrimaryKeyColumn() {
return primaryKeyColumn;
}
public compomenteABMCList getComponenteRef() {
return componenteRef;
}
public int getIndiceReal(int row) {
for (int i = 0; i < indexes.length; i++) {
if(indexes[i]==row)
return i;
}
return -1;
}
}