/*
 * Clase creada por Martin, modificada para su integracion con la herramienta.
 *
 *
 */
package com.uvigo.tMaestro.SCOCreator.tool.properties.cellEditors.contentEditors;

import com.uvigo.tMaestro.SCOCreator.tool.MainFrame;
import com.uvigo.tMaestro.SCOCreator.tool.MyFileFilter;
import com.uvigo.tMaestro.SCOCreator.tool.ImageView;
import com.uvigo.tMaestro.SCOCreator.tool.MyOptionPane;


import java.awt.*;
import java.beans.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import javax.xml.bind.*;
import com.uvigo.mhp.xml.menu.*;

public class MenuContentEditorPanel extends JPanel implements ContentEditorPanel {

    private DefaultTableModel tableModel;
    private JAXBContext jc;
    private ObjectFactory objFactory;
    private com.uvigo.mhp.xml.menu.Menu menu;
    private java.util.List elements;
    private MediaTracker trk;
    //Ruta hasta el directorio de la aplicacion
    private String sBase;
    //Ruta desde sBase hasta el directorio en donde esta el fichero xml
    private String sRuta;
    //Nombre del fichero .xml
    private String sFile;
    //Listado de ficheros anadidos desde este panel en algun momento.
    //Guarda tanto los actuales como los descartados
    private java.util.ArrayList<java.io.File> oAddedFiles = new java.util.ArrayList<java.io.File>();
    //Ruta al directorio del componente (dentro del directorio del proyecto). Desde /Projects
    private String sDir;
    /**
     * Referencia al dialogo que va a contener este panel
     */
    private ContentEditorDialog oDialog;
    
    /**
     * Constructor
     * @param sPathFile Ruta relativa al directorio de la aplicacion, del fichero .xml
     * @param oDialog Referencial al dialogo contenedor de este panel.
     */
    public MenuContentEditorPanel(String sPathFile, ContentEditorDialog oDialog) {
      if ((sPathFile==null)||(sPathFile.isEmpty())) sPathFile = "RESOURCES/MenuCE.xml";//M: inicializacion
       
        initComponents();
        this.oDialog = oDialog;

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{},
                new String[]{
            MainFrame.oMainFrame.getMessage("Title24"),
            MainFrame.oMainFrame.getMessage("Title19")
        }) {

            Class[] types = new Class[]{
                java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }
        });

        jLabel2.setBorder(new javax.swing.border.TitledBorder(MainFrame.oMainFrame.getMessage("Border7")));
        jLabel3.setBorder(new javax.swing.border.TitledBorder(MainFrame.oMainFrame.getMessage("Border8")));
        jButton10.setText(MainFrame.oMainFrame.getMessage("Button7"));
        jButton12.setText(MainFrame.oMainFrame.getMessage("Button6"));

        try {
            jc = JAXBContext.newInstance("com.uvigo.mhp.xml.menu");
            objFactory = new ObjectFactory();
            menu = objFactory.createMenu();
            elements = menu.getMenuElement();

            tableModel = (DefaultTableModel) jTable1.getModel();
            trk = new MediaTracker(this);
            jScrollPane2.getViewport().setBackground(Color.white);
            jScrollPane2.getViewport().setOpaque(true);

           sBase= new String (MainFrame.oMainFrame.sDir+ "/");
            sDir= new String("TEMP/COMPONENTS/");
            if (sPathFile != null) {
                //Parte de sPathFile que corresponde a ruta (que no es fichero)
                String[] split = sPathFile.split("/");
                sRuta = new String();
                int z = 0;
                for (z = 0; z < split.length - 1; z++) {
                    sRuta = sRuta.concat(split[z] + "/");
                }

                //Parte de sPathFile que corresponde al fichero
                sFile = split[split.length - 1];

                load(new java.io.File(sBase+sPathFile));
               
            }


        } catch (JAXBException ex) {
            System.out.println(ex.getMessage());
        }


    }

    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jPanel13 = new javax.swing.JPanel();
        jButton10 = new javax.swing.JButton();
        jButton12 = new javax.swing.JButton();
        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel20 = new javax.swing.JPanel();
        jPanel21 = new javax.swing.JPanel();
        jButton17 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jPanel22 = new javax.swing.JPanel();
        jPanel14 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jLabel2 = new javax.swing.JLabel();
        jPanel15 = new javax.swing.JPanel();
        jTextField2 = new javax.swing.JTextField();
        jPanel16 = new javax.swing.JPanel();
        jButton13 = new javax.swing.JButton();
        jButton14 = new javax.swing.JButton();
        jPanel17 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jLabel3 = new javax.swing.JLabel();
        jPanel18 = new javax.swing.JPanel();
        jTextField3 = new javax.swing.JTextField();
        jPanel19 = new javax.swing.JPanel();
        jButton15 = new javax.swing.JButton();
        jButton16 = new javax.swing.JButton();

        setLayout(new java.awt.BorderLayout());

        jPanel13.setLayout(new java.awt.GridLayout(1, 0));

        jButton10.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton10ActionPerformed(evt);
            }
        });

        jPanel13.add(jButton10);

        jButton12.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton12ActionPerformed(evt);
            }
        });

        jPanel13.add(jButton12);

        add(jPanel13, java.awt.BorderLayout.SOUTH);

        jSplitPane1.setDividerLocation(150);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jPanel20.setLayout(new java.awt.BorderLayout());

        jPanel21.setLayout(new java.awt.GridLayout(1, 0));

        jButton17.setText("+");
        jButton17.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton17ActionPerformed(evt);
            }
        });

        jPanel21.add(jButton17);

        jButton1.setText("-");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jPanel21.add(jButton1);

        jPanel20.add(jPanel21, java.awt.BorderLayout.SOUTH);

        jPanel1.setLayout(new java.awt.BorderLayout());

        jScrollPane2.setAutoscrolls(true);
        jTable1.setCellSelectionEnabled(true);
        jTable1.setEditingColumn(1);
        jTable1.setEditingRow(1);
        jTable1.setOpaque(false);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });

        jScrollPane2.setViewportView(jTable1);

        jPanel1.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        jPanel2.setLayout(new java.awt.GridLayout(0, 1));

        jButton2.setText("<");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jPanel2.add(jButton2);

        jButton3.setText(">");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jPanel2.add(jButton3);

        jPanel1.add(jPanel2, java.awt.BorderLayout.WEST);

        jPanel20.add(jPanel1, java.awt.BorderLayout.CENTER);

        jSplitPane1.setTopComponent(jPanel20);

        jPanel22.setLayout(new java.awt.GridLayout(1, 0));

        jPanel14.setLayout(new java.awt.BorderLayout());

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jScrollPane3.setViewportView(jLabel2);

        jPanel14.add(jScrollPane3, java.awt.BorderLayout.CENTER);

        jPanel15.setLayout(new java.awt.BorderLayout());

        jTextField2.setColumns(20);
        jTextField2.setEditable(false);
        jPanel15.add(jTextField2, java.awt.BorderLayout.CENTER);

        jPanel16.setLayout(new java.awt.GridLayout(1, 0));

        jButton13.setText("...");
        jButton13.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton13ActionPerformed(evt);
            }
        });

        jPanel16.add(jButton13);

        jButton14.setText("X");
        jButton14.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton14ActionPerformed(evt);
            }
        });

        jPanel16.add(jButton14);

        jPanel15.add(jPanel16, java.awt.BorderLayout.EAST);

        jPanel14.add(jPanel15, java.awt.BorderLayout.SOUTH);

        jPanel22.add(jPanel14);

        jPanel17.setLayout(new java.awt.BorderLayout());

        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jScrollPane4.setViewportView(jLabel3);

        jPanel17.add(jScrollPane4, java.awt.BorderLayout.CENTER);

        jPanel18.setLayout(new java.awt.BorderLayout());

        jTextField3.setColumns(20);
        jTextField3.setEditable(false);
        jPanel18.add(jTextField3, java.awt.BorderLayout.CENTER);

        jPanel19.setLayout(new java.awt.GridLayout(1, 0));

        jButton15.setText("...");
        jButton15.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton15ActionPerformed(evt);
            }
        });

        jPanel19.add(jButton15);

        jButton16.setText("X");
        jButton16.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton16ActionPerformed(evt);
            }
        });

        jPanel19.add(jButton16);

        jPanel18.add(jPanel19, java.awt.BorderLayout.EAST);

        jPanel17.add(jPanel18, java.awt.BorderLayout.SOUTH);

        jPanel22.add(jPanel17);

        jSplitPane1.setRightComponent(jPanel22);

        add(jSplitPane1, java.awt.BorderLayout.CENTER);

    }
    // </editor-fold>//GEN-END:initComponents
    private void jButton16ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton16ActionPerformed
    {//GEN-HEADEREND:event_jButton16ActionPerformed
        int i = jTable1.getSelectedRow();
        if (i == -1) return;

        MenuElementType met = (MenuElementType) elements.get(i);
        met.setNotSelectedImage("");
        jTextField3.setText("");
        jTextField3.setCaretPosition(0);
        jLabel3.setIcon(null);
    }//GEN-LAST:event_jButton16ActionPerformed

    private void jButton14ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton14ActionPerformed
    {//GEN-HEADEREND:event_jButton14ActionPerformed
        int i = jTable1.getSelectedRow();
        if (i == -1) return;

        MenuElementType met = (MenuElementType) elements.get(i);
        met.setSelectedImage("");
        jTextField2.setText("");
        jTextField2.setCaretPosition(0);
        jLabel2.setIcon(null);
    }//GEN-LAST:event_jButton14ActionPerformed

    private void jButton15ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton15ActionPerformed
    {//GEN-HEADEREND:event_jButton15ActionPerformed
        // Configurar la imagen de elemento no seleccionado

        int i = jTable1.getSelectedRow();
        if (i == -1) return;

        javax.swing.JFileChooser chooser = new javax.swing.JFileChooser();
        MyFileFilter oFilter = new MyFileFilter();
        oFilter.vAddExtension("jpeg");
        oFilter.vAddExtension("jpg");
        oFilter.vSetDescripcion(".jpeg");
        chooser.addChoosableFileFilter(oFilter);
        oFilter = new MyFileFilter();
        oFilter.vAddExtension("gif");
        oFilter.vSetDescripcion(".gif");
        chooser.addChoosableFileFilter(oFilter);
        oFilter = new MyFileFilter();
        oFilter.vAddExtension("png");
        oFilter.vSetDescripcion(".png");
        chooser.addChoosableFileFilter(oFilter);
        oFilter = new MyFileFilter();
        oFilter.vAddExtension("tif");
        oFilter.vAddExtension("tiff");
        oFilter.vSetDescripcion(".tiff");
        chooser.addChoosableFileFilter(oFilter);
        oFilter = new MyFileFilter();
        oFilter.vAddExtension("tif");
        oFilter.vAddExtension("tiff");
        oFilter.vAddExtension("jpeg");
        oFilter.vAddExtension("jpg");
        oFilter.vAddExtension("png");
        oFilter.vAddExtension("gif");
        oFilter.vSetDescripcion(".jpeg .tiff .gif .png");
        chooser.addChoosableFileFilter(oFilter);
        chooser.setAccessory(new ImageView(chooser));
        chooser.setCurrentDirectory(MainFrame.oMainFrame.getLastDir());
        boolean bExit = false;
        while (!bExit) {
            int option = chooser.showOpenDialog(this);
            if (option == javax.swing.JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
              //Si existe un fichero con el mismo nombre entre los elementos que el usuario ha configurado, lo avisamos
                if (new java.io.File(sBase + sDir, file.getName()).exists()) {
                    int iOption = MyOptionPane.showConfirmDialog(MainFrame.oMainFrame, MainFrame.oMainFrame.getMessage("Question4"), MainFrame.oMainFrame.getMessage("Title2"), javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE);
                    if (iOption == javax.swing.JOptionPane.NO_OPTION) continue;
                }
                bExit = true;
                try {
                    setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
                    MainFrame.oMainFrame.setLastDir(file.getParentFile());
                    java.io.File oDirComponent = new java.io.File(sBase + sDir);
                    oDirComponent.mkdir();
                    java.io.File oImage = new java.io.File(oDirComponent, file.getName());
                    MainFrame.copyFile(file, oImage);
                    oAddedFiles.add(oImage);


                    URL url = new URL("file:/" + sBase + sDir + file.getName());
                    Image temp = Toolkit.getDefaultToolkit().getImage(url);
                    trk.addImage(temp, 0);
                    trk.waitForAll();

                    MenuElementType met = (MenuElementType) elements.get(i);
                    met.setNotSelectedImage(file.getName());
                    jTextField3.setText(file.getName());
                    jTextField3.setCaretPosition(0);
                    jLabel3.setIcon(new ImageIcon(temp));
                } catch (Exception ex) {
                    System.out.println(ex);
                }
                setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
            } else bExit = true;
        }
    }//GEN-LAST:event_jButton15ActionPerformed

    private void jButton13ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton13ActionPerformed
    {//GEN-HEADEREND:event_jButton13ActionPerformed
        // Configurar la imagen de elemento seleccionado

        int i = jTable1.getSelectedRow();
        if (i == -1) return;

        javax.swing.JFileChooser chooser = new javax.swing.JFileChooser();
        MyFileFilter oFilter = new MyFileFilter();
        oFilter.vAddExtension("jpeg");
        oFilter.vAddExtension("jpg");
        oFilter.vSetDescripcion(".jpeg");
        chooser.addChoosableFileFilter(oFilter);
        oFilter = new MyFileFilter();
        oFilter.vAddExtension("gif");
        oFilter.vSetDescripcion(".gif");
        chooser.addChoosableFileFilter(oFilter);
        oFilter = new MyFileFilter();
        oFilter.vAddExtension("png");
        oFilter.vSetDescripcion(".png");
        chooser.addChoosableFileFilter(oFilter);
        oFilter = new MyFileFilter();
        oFilter.vAddExtension("tif");
        oFilter.vAddExtension("tiff");
        oFilter.vSetDescripcion(".tiff");
        chooser.addChoosableFileFilter(oFilter);
        oFilter = new MyFileFilter();
        oFilter.vAddExtension("tif");
        oFilter.vAddExtension("tiff");
        oFilter.vAddExtension("jpeg");
        oFilter.vAddExtension("jpg");
        oFilter.vAddExtension("png");
        oFilter.vAddExtension("gif");
        oFilter.vSetDescripcion(".jpeg .tiff .gif .png");
        chooser.addChoosableFileFilter(oFilter);
        chooser.setAccessory(new ImageView(chooser));
        chooser.setCurrentDirectory(MainFrame.oMainFrame.getLastDir());
        boolean bExit = false;
        while (!bExit) {
            int option = chooser.showOpenDialog(this);
            if (option == javax.swing.JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
               //Si existe un fichero con el mismo nombre entre los elementos que el usuario ha configurado, lo avisamos
                if (new java.io.File(sBase + sDir, file.getName()).exists()) {
                    int iOption = MyOptionPane.showConfirmDialog(MainFrame.oMainFrame, MainFrame.oMainFrame.getMessage("Question4"), MainFrame.oMainFrame.getMessage("Title2"), javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE);
                    if (iOption == javax.swing.JOptionPane.NO_OPTION) continue;
                }
                bExit = true;
                try {
                    setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
                    MainFrame.oMainFrame.setLastDir(file.getParentFile());
                    java.io.File oDirComponent = new java.io.File(sBase + sDir);
                    oDirComponent.mkdir();
                    java.io.File oImage = new java.io.File(oDirComponent, file.getName());
                    MainFrame.copyFile(file, oImage);
                    oAddedFiles.add(oImage);

                    URL url = new URL("file:/" + sBase + sDir + file.getName());
                    Image temp = Toolkit.getDefaultToolkit().getImage(url);
                    trk.addImage(temp, 0);
                    trk.waitForAll();

                    MenuElementType met = (MenuElementType) elements.get(i);
                    met.setSelectedImage(file.getName());
                    jTextField2.setText(file.getName());
                    jTextField2.setCaretPosition(0);
                    jLabel2.setIcon(new ImageIcon(temp));
                } catch (Exception ex) {
                    System.out.println(ex);
                }
                setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
            } else bExit = true;
        }
    }//GEN-LAST:event_jButton13ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton2ActionPerformed
    {//GEN-HEADEREND:event_jButton2ActionPerformed
        // Hay que desplazar una fila hacia arriba
        int i = jTable1.getSelectedRow();
        if (i <= 0) return;

        tableModel.moveRow(i, i, i - 1);
        Object ob1 = elements.get(i);
        Object ob2 = elements.get(i - 1);
        elements.set(i, ob2);
        elements.set(i - 1, ob1);

        jTable1.setColumnSelectionInterval(0, 0);
        jTable1.setRowSelectionInterval(i - 1, i - 1);
        select(jTable1.getSelectedRow());
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton3ActionPerformed
    {//GEN-HEADEREND:event_jButton3ActionPerformed
        // Hay que desplazar una fila hacia abajo

        int i = jTable1.getSelectedRow();
        if (i >= tableModel.getRowCount() - 1) return;

        tableModel.moveRow(i, i, i + 1);
        Object ob1 = elements.get(i);
        Object ob2 = elements.get(i + 1);
        elements.set(i, ob2);
        elements.set(i + 1, ob1);

        jTable1.setColumnSelectionInterval(0, 0);
        jTable1.setRowSelectionInterval(i + 1, i + 1);
        select(jTable1.getSelectedRow());
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton1ActionPerformed
    {//GEN-HEADEREND:event_jButton1ActionPerformed
        // eliminar las filas seleccionadas

        int i[] = jTable1.getSelectedRows();
        if (i.length == 0) return;

        for (int j = 0; j < i.length; j++) {
            tableModel.removeRow(i[j] - j);
            elements.remove(i[j] - j);
        }

        if (jTable1.getRowCount() == 0) return;
        if (i[0] == jTable1.getRowCount()) {
            jTable1.setColumnSelectionInterval(0, 0);
            jTable1.setRowSelectionInterval(i[0] - 1, i[0] - 1);
        } else {
            jTable1.setColumnSelectionInterval(0, 0);
            jTable1.setRowSelectionInterval(i[0], i[0]);
        }
        select(jTable1.getSelectedRow());
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton17ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton17ActionPerformed
    {//GEN-HEADEREND:event_jButton17ActionPerformed
        // Insertar una fila
        try {
            Object temp[] = new Object[2];
            temp[0] = new String("");
            temp[1] = new String("");
            tableModel.addRow(temp);

            MenuElementType met = objFactory.createMenuElementType();
            met.setLabel("");
            met.setContextName("");
            met.setNotSelectedImage("");
            met.setSelectedImage("");

            elements.add(met);

            jTable1.setColumnSelectionInterval(0, 0);
            jTable1.setRowSelectionInterval(jTable1.getRowCount() - 1, jTable1.getRowCount() - 1);
            select(jTable1.getRowCount() - 1);
        } catch (Exception ex) {
        }
    }//GEN-LAST:event_jButton17ActionPerformed

    /**
     * El usuario ha pulsado sobre cancelar
     */
    private void jButton12ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton12ActionPerformed
    {//GEN-HEADEREND:event_jButton12ActionPerformed
        oDialog.setAction(ContentEditorDialog.CANCEL, null);
        oDialog.dispose();
    }//GEN-LAST:event_jButton12ActionPerformed

    private void load(java.io.File file) {
        // Hay que cargar el contenido de un fichero XML.
        try {

            if (file == null) return;

            int i = tableModel.getRowCount();
            for (int j = 0; j < i; j++)
                tableModel.removeRow(0);

            Unmarshaller u = jc.createUnmarshaller();
            u.setValidating(true);
            menu = (com.uvigo.mhp.xml.menu.Menu) u.unmarshal(new FileInputStream(file));
            elements = menu.getMenuElement();

            for (int k = 0; k < elements.size(); k++) {
                Object temp[] = new Object[2];
                temp[0] = ((MenuElementType) elements.get(k)).getLabel();
                temp[1] = ((MenuElementType) elements.get(k)).getContextName();

                tableModel.addRow(temp);
            }

            if (tableModel.getRowCount() == 0) return;

            jTable1.setColumnSelectionInterval(0, 0);
            jTable1.setRowSelectionInterval(0, 0);
            select(0);
        } catch (Exception ex) {
            System.out.println(ex);
        }

    }

    /**
     * El usuario ha pulsado sobre el bot�n OK
     */
    private void jButton10ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton10ActionPerformed
    {//GEN-HEADEREND:event_jButton10ActionPerformed
        // Hay que grabar un fichero XML con el contenido creado, en el
        // directorio del proyecto (dentro del directorio de componente).
        // Ademas hay que copiar las imagenes al mismo directorio
        // Hay que actualizar los campos de texto a los valores indicados en la tabla.


        try {
            setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
            java.io.File oDirComponent = new java.io.File(sBase + sDir);
            oDirComponent.mkdir();
           if (!sFile.contains("(")) sFile = new String("(" + MainFrame.oMainFrame.getPSheet().getSelectedOption() + ")" + 
                            MainFrame.oMainFrame.oGetCapsulaActiva().oGetBean().getName()+".xml");//M: le damos el nombre del componente
            java.io.File oFile = new File(oDirComponent, sFile);
            java.util.ArrayList<java.io.File> oFiles = new java.util.ArrayList<java.io.File>();

            for (int i = 0; i < tableModel.getRowCount(); i++) {
                MenuElementType met = (MenuElementType) elements.get(i);
                met.setLabel((String) tableModel.getValueAt(i, 0));
                met.setContextName((String) tableModel.getValueAt(i, 1));

                //Copiamos las imagenes "seleccionadas"
                java.io.File oComponentFile = new java.io.File(oDirComponent, met.getSelectedImage());
                oFiles.add(oComponentFile);
                if (!oComponentFile.exists()) {
                    MainFrame.copyFile(new java.io.File(sBase+sRuta+met.getSelectedImage()), oComponentFile);
                    }

                //Copiamos las imagenes "no seleccionadas"
                oComponentFile = new java.io.File(oDirComponent, met.getNotSelectedImage());
                oFiles.add(oComponentFile);
                if (!oComponentFile.exists()) {
                    MainFrame.copyFile(new java.io.File(sBase+sRuta+met.getNotSelectedImage()), oComponentFile);
                   }
            }

            Marshaller m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            oFiles.add(oFile);
            m.marshal(menu, new FileOutputStream(oFile));
            MainFrame.oMainFrame.getEditionProperty().putOptionFiles(oFiles, MainFrame.oMainFrame.getPSheet().getSelectedOption());
            oDialog.setAction(ContentEditorDialog.OK, sDir + sFile);
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println(ex);
            oDialog.setAction(ContentEditorDialog.CANCEL, null); // Si se produce algun error es como cancelar el proceso

        }
        setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
        oDialog.dispose();
        
        
    }//GEN-LAST:event_jButton10ActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_jTable1MouseClicked
    {//GEN-HEADEREND:event_jTable1MouseClicked
        // Cuando se selecciona una fila de la tabla hay que mostrar las imagenes asociadas
        Point p = new Point(evt.getX(), evt.getY());
        int fil = jTable1.rowAtPoint(p);
        if (fil == -1) return;
        select(fil);
    }//GEN-LAST:event_jTable1MouseClicked

    private void select(int fil) {
        MenuElementType met = (MenuElementType) elements.get(fil);
        try {
            if ((met.getSelectedImage() != null) && (!(met.getSelectedImage().equals("")))) {

                //Hacemos esto en lugar de verificar si el fichero existe (oFile.exists())
                //porque por algun motivo que desconozco la funci�n exists en algunas ocasiones
                //existiendo el fichero devuelve un false. As� nos curamos en salud.
                Image img = Toolkit.getDefaultToolkit().createImage(new URL("file:/" + sBase + sDir + met.getSelectedImage()));
                trk.addImage(img, 0);
                trk.waitForAll();
                if (img.getWidth(null) == -1) {
                    img=Toolkit.getDefaultToolkit().createImage(new URL("file:/"+sBase+sRuta+met.getSelectedImage()));
                   }
                trk.addImage(img, 0);
                trk.waitForAll();

                if ((img != null) && (img.getWidth(null) != -1) && (img.getHeight(null) != -1)) {
                    jLabel2.setIcon(new ImageIcon(img));
                    jTextField2.setText(met.getSelectedImage());
                    jTextField2.setCaretPosition(0);
                }
            } else {
                jLabel2.setIcon(null);
                jTextField2.setText("");
                jTextField2.setCaretPosition(0);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        try {
            if ((met.getNotSelectedImage() != null) && (!(met.getNotSelectedImage().equals("")))) {
                //Hacemos esto en lugar de verificar si el fichero existe (oFile.exists())
                //porque por algun motivo que desconozco la funcion exists en algunas ocasiones
                //existiendo el fichero devuelve un false. Asi nos curamos en salud.
                Image img = Toolkit.getDefaultToolkit().createImage(new URL("file:/" + sBase + sDir + met.getNotSelectedImage()));
                trk.addImage(img, 0);
                trk.waitForAll();
                if (img.getWidth(null) == -1) {
                     img=Toolkit.getDefaultToolkit().createImage(new URL("file:/"+sBase+sRuta+met.getNotSelectedImage()));
                     }
                trk.addImage(img, 0);
                trk.waitForAll();

                if ((img != null) && (img.getWidth(null) != -1) && (img.getHeight(null) != -1)) {
                    jLabel3.setIcon(new ImageIcon(img));
                    jTextField3.setText(met.getNotSelectedImage());
                    jTextField3.setCaretPosition(0);
                }
            } else {
                jLabel3.setIcon(null);
                jTextField3.setText("");
                jTextField3.setCaretPosition(0);
            }
        } catch (Exception ex) {
        }
    }

    public Dimension getPreferredSize() {
        return new Dimension(600, 400);
    }

    /**
     * Devuelve los ficheros anadidos
     */
    public java.util.ArrayList<java.io.File> getFiles() {
        return oAddedFiles;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton10;
    private javax.swing.JButton jButton12;
    private javax.swing.JButton jButton13;
    private javax.swing.JButton jButton14;
    private javax.swing.JButton jButton15;
    private javax.swing.JButton jButton16;
    private javax.swing.JButton jButton17;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel13;
    private javax.swing.JPanel jPanel14;
    private javax.swing.JPanel jPanel15;
    private javax.swing.JPanel jPanel16;
    private javax.swing.JPanel jPanel17;
    private javax.swing.JPanel jPanel18;
    private javax.swing.JPanel jPanel19;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel20;
    private javax.swing.JPanel jPanel21;
    private javax.swing.JPanel jPanel22;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    // End of variables declaration//GEN-END:variables
}
