Package com.GestDB.swing.table

Source Code of com.GestDB.swing.table.CellEditor

/*
* CellEditor.java
*
* Created on 27 de septiembre de 2006, 12:45
* Created by Arsenio Molinero
* Copyright (C) 2004, 2005, 2006 Arsenio Molinero
*
* GestDB - a Java multi database client
*
* This file is part of GestDB.
*
* GestDB is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GestDB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GestDB; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

package com.GestDB.swing.table;

import java.sql.Clob;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Component;
import com.GestDB.Gestor;
import com.GestDB.general.Trackbug;
import com.GestDB.sql.SortTModel;
import com.GestDB.swing.DatePickerObserver;
import java.math.BigInteger;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import javax.swing.text.DateFormatter;

/**
*
* @author seni
*/
public class CellEditor extends AbstractCellEditor
    implements TableCellEditor, ActionListener {
   
    JColorChooser colorChooser = null;
    JDialog dialog = null;
    FontEditor jiFontEditor = null;
    ClobEditor jiClobEditor = null;
    JButton boton = new JButton();
    protected static final String EDITCOLOR = "editcolor";
    protected static final String EDITBOOLEAN = "editboolean";
    protected static final String EDITFONT = "editfont";
    protected static final String EDITIMAGE = "editimage";
    protected static final String EDITSTRING = "editstring";
    protected static final String EDITFORMATTER = "editformatter";
    protected static final String EDITDATE = "editdate";
    protected static final String EDITCOMBO = "editcombo";
    protected static final String EDITCLOB = "editclob";

    private Object valor = null;
    private Gestor gestor = null;

    /**
     * Constructs a <code>CellEditor</code> no usa nada
     *
     */
    public CellEditor(Gestor gestor) {
        this.gestor = gestor;
        colorChooser = new JColorChooser();
        dialog = JColorChooser.createDialog(boton,Gestor.GetLiteral("celleditor.choise_color","Seleccione un color"),true,  //modal
            colorChooser, this,  null);
    }
   
    public void actionPerformed(ActionEvent e) {
        if (EDITCOLOR.equals(e.getActionCommand())) {
            //The user has clicked the cell, so
            //bring up the dialog.
            if(valor instanceof  Color)
            {
                Color newColor = (Color)valor;
                JButton button = (JButton)e.getSource();
                button.setBackground(newColor);
                colorChooser.setColor(newColor);
                dialog.setVisible(true);
                valor = colorChooser.getColor();
                //Make the renderer reappear.
                fireEditingStopped();
            }
        } else if (EDITCLOB.equals(e.getActionCommand())) {
            String cadena = "";
            if(valor != null)
            {
                try {
                    cadena = ((java.sql.Clob) valor).getSubString(1L, (int)((java.sql.Clob) valor).length());
                } catch (SQLException ex) {
                    Trackbug.error(ex, ex.getMessage());
                }
            }

            jiClobEditor = new ClobEditor(this);
            jiClobEditor.setTexto(cadena);
            gestor.addInternalFrameToDestock(jiClobEditor);
            // la recogida se hace asincrona, es decir hay que esperar a que el clob editor nos diga que ok
        } else if (EDITFONT.equals(e.getActionCommand())) {
            if(valor instanceof  Font)
            {
                Font newFont = (Font)valor;
                JButton button = (JButton)e.getSource();
                button.setFont(newFont);
                jiFontEditor = new FontEditor(this);
                jiFontEditor.setFuente(newFont);
                gestor.addInternalFrameToDestock(jiFontEditor);
                // la recogida se hace asincrona, es decir hay que esperar a que el font editor nos diga que ok
            }
        } else if (EDITIMAGE.equals(e.getActionCommand())) {
            if(valor instanceof  ImageData)
            {
                ImageData newImage = (ImageData)valor;
                JButton button = (JButton)e.getSource();
                button.setIcon(newImage);
               
                JFileChooser jfc = new JFileChooser();
                jfc.setFileSelectionMode(jfc.FILES_AND_DIRECTORIES);
                jfc.setDialogType(javax.swing.JFileChooser.OPEN_DIALOG);
               
                jfc.setFileFilter(new javax.swing.filechooser.FileFilter(){
                    private Vector vExtension = null;

                    public boolean accept(java.io.File file) {
                        if(vExtension == null)
                        {
                            String extensiones[] = {"png","jpg","gif"};
                            vExtension = new Vector(extensiones.length,10);
                            for(int i =0; i< extensiones.length;i++)
                                vExtension.addElement(extensiones[i].trim().toLowerCase());
                        }

                        String nombre = file.getName().trim().toLowerCase();
                        if(nombre.indexOf(".") != -1)
                            nombre = nombre.substring(nombre.lastIndexOf(".")+1);

                        if(vExtension.contains(nombre))
                            return true;

                        return false;
                    }

                    public String getDescription()
                    {
                        return Gestor.GetLiteral("celleditor.files_img","Archivos de imagenes") + " png, jpg, gif";
                    }
                });
                if(Gestor.propiedades.containsKey("conexion.exportar.ultimo_dir_html"))
                    jfc.setCurrentDirectory(new File((String)Gestor.propiedades.get("conexion.exportar.ultimo_dir_html")));
                if(jfc.showOpenDialog(button) == javax.swing.JFileChooser.APPROVE_OPTION)
                {
                    Gestor.propiedades.put("conexion.exportar.ultimo_dir_html", jfc.getCurrentDirectory().getAbsolutePath());
                    // el archivo lo tenemos en jfc.getSelectedFile(), lo tenemos que copiar la a ruta tmp
                    // comprobamos que el directorio tmp existe y si no existe lo creamos
                    String dirbasetmp = Gestor.getRutaBaseTmp();
                   
                    if(com.utils.utilidades.copyFile(jfc.getSelectedFile(), new File(dirbasetmp)))
                    {
                        // tenemos que crear el objeto image
                        File archivoImagen = new File(dirbasetmp,jfc.getSelectedFile().getName());
                        if(archivoImagen.exists() || archivoImagen.canRead())
                            valor = new ImageData(archivoImagen.getAbsolutePath(),jfc.getSelectedFile().getName());
                    }
                    else
                    {
                        // no se puede copiar el archivo
                        com.GestDB.swing.Alerta al = new com.GestDB.swing.Alerta(new javax.swing.JDialog(),
                                Gestor.GetLiteral("gestor.alert","Aviso"),true,
                                Gestor.GetLiteral("editskin.error7","No se ha podido copiar el archivo"),
                                com.GestDB.swing.Alerta.OK);
                        al.setVisible(true);
                        al = null;
                    }
                   
                }
               
                fireEditingStopped();
            }
        } else if (EDITBOOLEAN.equals(e.getActionCommand())) {
            if(valor instanceof  Boolean)
            {
                JCheckBox jck = (JCheckBox)e.getSource();
                valor = Boolean.valueOf(jck.isSelected());
            }
        } else if (EDITSTRING.equals(e.getActionCommand())) {
            if(valor instanceof  String)
            {
                JTextField jtf = (JTextField)e.getSource();
                valor = jtf.getText();
                fireEditingStopped();
            }
        } else if (EDITFORMATTER.equals(e.getActionCommand())) {
            JFormattedTextField jtf = (JFormattedTextField)e.getSource();
            valor = jtf.getValue();
            fireEditingStopped();
        } else if (EDITDATE.equals(e.getActionCommand())) {
            if(e.getSource() instanceof DatePickerObserver)
                valor = new Timestamp(((DatePickerObserver)e.getSource()).getValue().getTime());
            else
                valor = new Timestamp(((java.util.Date)((JFormattedTextField)e.getSource()).getValue()).getTime());
            fireEditingStopped();
        } else if (EDITCOMBO.equals(e.getActionCommand())) {
            if(valor instanceof  JComboBox)
            {
                JComboBox jb = (JComboBox)e.getSource();
                valor = jb;
                fireEditingStopped();
            }
        } else { //User pressed dialog's "OK" button.
            if(valor instanceof  Color)
            {
            valor = colorChooser.getColor();
            }
        }
    }

    public Object getCellEditorValue() {
        return valor;
    }

    public Component getTableCellEditorComponent(JTable table,
                                                 Object value,
                                                 boolean isSelected,
                                                 int row,
                                                 int column)
    {
        Class clase = ((SortTModel)table.getModel()).getColumnClass(column);
        valor = value;
        if(clase == Boolean.class)
        {
            boolean boleano = ((Boolean)valor).booleanValue();
            JCheckBox jck = new JCheckBox("" + boleano,boleano);
            jck.setActionCommand(EDITBOOLEAN);
            jck.addActionListener(this);
            return jck;
        }
        else if(clase == Color.class && valor != null)
        {
            JButton button = new JButton();
            button.setActionCommand(EDITCOLOR);
            button.addActionListener(this);
            button.setBorderPainted(false);
            return button;
        }
        else if(clase == Font.class && valor != null)
        {
            JButton button = new JButton();
            button.setActionCommand(EDITFONT);
            button.addActionListener(this);
            button.setBorderPainted(false);
            return button;
        }
        else if(clase == ImageData.class && valor != null)
        {
            JButton button = new JButton();
            button.setActionCommand(EDITIMAGE);
            button.addActionListener(this);
            button.setBorderPainted(false);
            button.setIcon((ImageData)valor);
            return button;
        }
        else if(clase == String.class)
        {
            String texto = "";
            if(valor != null)
                texto = (String)valor;
           
            JTextField jtf = new JTextField();
            jtf.setActionCommand(EDITSTRING);
            jtf.setText(texto);
            jtf.setFont(jtf.getFont().deriveFont(Font.BOLD));
            jtf.addActionListener(this);
            return jtf;
        }
        else if(clase == Integer.class || clase == Float.class || clase == Double.class || clase == BigInteger.class ||
                clase == java.sql.Time.class)
        {
            try {
               
                JFormattedTextField jtf = new JFormattedTextField();
                if(valor != null)
                    jtf.setValue(valor);
                jtf.setActionCommand(EDITFORMATTER);
                jtf.setFont(jtf.getFont().deriveFont(Font.BOLD));
                jtf.addActionListener(this);
                return jtf;
            } catch (Exception ex) {
                JTextField jtf = new JTextField();
                jtf.setActionCommand(EDITSTRING);
                if(valor != null)
                    jtf.setText(valor.toString());
                jtf.setFont(jtf.getFont().deriveFont(Font.BOLD));
                jtf.addActionListener(this);
                return jtf;
            }
        }
        else if(clase == java.sql.Date.class || clase == java.sql.Timestamp.class)
        {
            try {
                DateFormatter df = new DateFormatter(DateFormat.getDateTimeInstance());
                DatePickerObserver dpo = new DatePickerObserver (df);
                if(valor == null)
                    dpo.setValue(new Date());
                else if(valor instanceof java.sql.Date)
                    dpo.setValue(new Date(((java.sql.Date)valor).getTime()));
                else
                    dpo.setValue(new Date(((java.sql.Timestamp)valor).getTime()));
                dpo.setActionCommand(EDITDATE);
                dpo.setFont(dpo.getFont().deriveFont(Font.BOLD));
                dpo.addActionListener(this);
                return dpo;
            } catch (Exception ex) {
                JTextField jtf = new JTextField();
                jtf.setActionCommand(EDITSTRING);
                if(valor != null)
                    jtf.setText(valor.toString());
                jtf.setFont(jtf.getFont().deriveFont(Font.BOLD));
                jtf.addActionListener(this);
                return jtf;
            }
        }
        else if(clase == JLabel.class && valor != null)
        {
            JLabel jl = (JLabel)valor;
            return jl;
        }
        else if(clase == JComboBox.class && valor != null)
        {
            JComboBox jb = (JComboBox)valor;
            jb.setActionCommand(EDITCOMBO);
            jb.addActionListener(this);
            return jb;
        }
        else if(clase == java.sql.Clob.class)
        {
            JButton button = new JButton();
            button.setActionCommand(EDITCLOB);
            button.addActionListener(this);
            button.setBorderPainted(false);
            return button;
        }
       
        return boton;
    }

    public void EndEditing()
    {
        fireEditingStopped();
    }

    public void setFuente(Font fuente)
    {
        valor = fuente;
        fireEditingStopped();
    }

    public void setTexto(String texto)
    {

        if(valor instanceof java.sql.Clob)
        {
            try {
                valor = (java.sql.Clob) new java.sql.Clob() {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();

                public long length() throws SQLException {
                    return (long)bout.size();
                }

                public String getSubString(long pos, int length) throws SQLException {
                    int length2 = length;
                    int pos2 = (int)pos - 1;
                    String cadena = bout.toString();

                    if(pos2 < 0)
                        pos2 = 0;

                    if(pos2 >= cadena.length())
                        return "";

                    if((length2 + pos2) >= cadena.length())
                        length2 = cadena.length() - pos2;

                    return cadena.substring(pos2, length2);
                }

                public Reader getCharacterStream() throws SQLException {
                    StringReader sr = new StringReader(bout.toString());
                    return sr;
                }

                public InputStream getAsciiStream() throws SQLException {
                    ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
                    return bin;
                }

                public long position(String searchstr, long start) throws SQLException {
                    return bout.toString().indexOf(searchstr,(int)start - 1);
                }

                public long position(Clob searchstr, long start) throws SQLException {
                    throw new UnsupportedOperationException("Not supported yet.");
                }

                public int setString(long pos, String str) throws SQLException {
                    byte bcadena[] = str.getBytes();
                    bout.write(bcadena, 0, bcadena.length);
                    return bcadena.length;
                }

                public int setString(long pos, String str, int offset, int len) throws SQLException {
                    byte bcadena[] = str.getBytes();
                    bout.write(bcadena, offset, len);
                    return len;
                }

                public OutputStream setAsciiStream(long pos) throws SQLException {
                    throw new UnsupportedOperationException("Not supported yet.");
                }

                public Writer setCharacterStream(long pos) throws SQLException {
                    throw new UnsupportedOperationException("Not supported yet.");
                }

                public void truncate(long len) throws SQLException {
                    throw new UnsupportedOperationException("Not supported yet.");
                }

                public void free() throws SQLException {
                    bout.reset();
                }

                public Reader getCharacterStream(long pos, long length) throws SQLException {
                    StringReader sr = new StringReader(bout.toString().substring((int)pos, (int)pos + (int)length));
                    return sr;
                }
            }
           
            ((java.sql.Clob) valor).setString(0, texto);
                /*
                try {
                Writer wri = ((java.sql.Clob) valor).setCharacterStream(0L);
                wri.write(texto);
                wri.flush();
                wri.close();
                //                ((java.sql.Clob) valor).setString(0L, texto);
                } catch (IOException ex) {
                Logger.getLogger(CellEditor.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                System.out.println("Error: " + ex.getMessage());
                }
                 *
                 */
            } catch (SQLException ex) {
                Logger.getLogger(CellEditor.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        else
            valor = texto;

        fireEditingStopped();
    }
} // End of class CellEditor
TOP

Related Classes of com.GestDB.swing.table.CellEditor

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.