import java.net.URL;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;
import java.util.Optional;

import javax.swing.table.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;


import java.awt.event.*;
import java.io.File;

import javax.swing.*;
import javax.swing.event.CellEditorListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileNameExtensionFilter;

import java.awt.*;

public class jtabpane03 extends JDialog 
{
	
	private	JPanel	panel1;
	private	JPanel	panel2;
	private	JPanel	panel3;
	private	JPanel	panel4;
	
	private JTable table;
	private static final int BOOLEAN_COLUMN_INDEX = 0;
	private String[] toolTipStr = {"Select/Deselect all" , "aqw"      ,"Java","French","Latin"};
	
	private JTextField filterText;
	private JLabel lbl_filter;
	
	private JLabel	lbl_nb_rows;
	
	private JTree tree_plan;
	private JTable table_plan;
	
	//private JTable table_1;
	
	TreeModelPlanObj  model_load_datas;
	boolean flag_load_datas = false;
	
	private ArrayList<String> tree_datas = new ArrayList<String>();
	private ArrayList<String> tmp_tree_datas = new ArrayList<String>();
	
	private Class_plan intermediaire = new Class_plan();
	
	private String mouse_click = "";
	
	private TableModel model;
	
	//private TableModel modelzzz;
	
	private TableModel modelbis;
	
	private TreeModel treemodel;
	private List<TreeNode[]> expanded;
	
	private DefaultTableModel tableModel; 
	
	private WriteXML WRITE_XML; 
	private ReadXML READ_XML; 
	
	public jtabpane03(JFrame f, boolean modal) 
	{
	       super(f, modal);
	       
	       WRITE_XML = new WriteXML();
	       READ_XML = new ReadXML();
	      
	       // fermer la fenetre
	       addWindowListener(new java.awt.event.WindowAdapter() 
	       {
	           public void windowClosing(java.awt.event.WindowEvent e) 
	           {
	        	   dispose();
	           }
	       });
	      
	       try { 
	    	   
	            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); 
	            //UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");  
	            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");  
	            // com.sun.java.swing.plaf.windows.WindowsLookAndFeel
	            
	        } 
	        catch (Exception e) { 
	            System.out.println("Look and Feel not set"); 
	        } 
	       
	       
	       expanded = new ArrayList<TreeNode[]>();
	       
	       init();
	}
	

	class TextAreaRenderer extends JScrollPane implements TableCellRenderer
	{
	   JTextArea textarea;
	  
	   public TextAreaRenderer() 
	   {
	      textarea = new JTextArea();
	      textarea.setLineWrap(true);
	      textarea.setWrapStyleWord(true);
	      //textarea.setBorder(new TitledBorder("This is a JTextArea"));
	      getViewport().add(textarea);
	   }
	  
	   public Component getTableCellRendererComponent(JTable table, Object value,
	                                  boolean isSelected, boolean hasFocus,
	                                  int row, int column)
	   {
	      if (isSelected) 
	      {
	         setForeground(table.getSelectionForeground());
	         setBackground(table.getSelectionBackground());
	         textarea.setForeground(table.getSelectionForeground());
	         textarea.setBackground(table.getSelectionBackground());
	      } 
	      else 
	      {
	         setForeground(table.getForeground());
	         setBackground(table.getBackground());
	         textarea.setForeground(table.getForeground());
	         textarea.setBackground(table.getBackground());
	      }
	  
	      textarea.setText((String) value);
	      textarea.setCaretPosition(0);
	      return this;
	   }
	}
	  
	class TextAreaEditor extends DefaultCellEditor 
	{
		protected JScrollPane scrollpane;
		protected JTextArea textarea;
	  
		public TextAreaEditor() 
		{
			super(new JCheckBox());
			scrollpane = new JScrollPane();
			textarea = new JTextArea(); 
			textarea.setLineWrap(true);
			textarea.setWrapStyleWord(true);
			//textarea.setBorder(new TitledBorder("This is a JTextArea"));
			scrollpane.getViewport().add(textarea);
	   }
	  
	   public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) 
	   {
		   textarea.setText((String) value);
	       return scrollpane;
	   }
	  
	   public Object getCellEditorValue() 
	   {
	      return textarea.getText();
	   }
	} 
	
  
	private void init()
	{
		setResizable( false );
		setBounds(0, 0, 1000, 650);
		
		setTitle("Tabpane3 - debug ...");
     	
		ImageIcon icon = null;
		icon = createImageIcon("resources/settings.png", "");
		setIconImage( icon.getImage() );
		
		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
				
		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		tabbedPane.setBounds(0, 0, 984, 465);
		getContentPane().add(tabbedPane);
		
		String[] columnNames =  { "", "Test", "Deux" , "rien", "plus"};
		
	    Object[][] data = 
	    	{
	            { Boolean.TRUE, "USA", "Washington DC", "179", "false"},
	            { Boolean.TRUE, "Canada", "Ottawa", "32", "true"},
	            { Boolean.TRUE, "United Kingdom", "London", "60", "false"},
	            { Boolean.TRUE, "Germany", "Berlin", "83", "true"},
	            { Boolean.TRUE, "France", "Paris", "28", "true"},
	            { Boolean.FALSE, "Norway", "Oslo", "79", "false"},
	            { Boolean.TRUE, "India", "New Delhi", "1079", "false"},
	            { Boolean.TRUE, "USA", "Washington DC", "179", "false"},
	            { Boolean.TRUE, "Canada", "Ottawa", "32", "true"},
	            { Boolean.TRUE, "United Kingdom", "London", "60", "false"},
	            { Boolean.TRUE, "Germany", "Berlin", "83", "true"},
	            { Boolean.TRUE, "France", "Paris", "28", "true"},
	            { Boolean.FALSE, "Norway", "Oslo", "79", "false"},
	            { Boolean.TRUE, "India", "New Delhi", "1079", "false"}
	        };
		
		
	    TableModel model = new DefaultTableModel(data,  columnNames)
	    {		
	    	@Override
		    public boolean isCellEditable(int row, int column)
		    {
	    		// make read only fields except column 0,13,14
		        return column == 0 ;
	        }
	    	
	    	@Override
	        public Class<?> getColumnClass(int columnIndex) 
	    	{
	            if (columnIndex == 0) 
	            {
	                return Boolean.class;
	            } 
	            else 
	            {
	                return String.class;
	            }
	        }
	    };
	    
	   
	    JTable table =new JTable(model);    
	    	    
	    JTableHeader Theader = table.getTableHeader();
        
        Theader.setBackground(Color.red); // change the Background color
        Theader.setForeground(Color.WHITE); // change the Foreground
        
        Theader.setFont(new Font("Tahome", Font.BOLD, 20)); // font name style size
        ((DefaultTableCellRenderer)Theader.getDefaultRenderer()) .setHorizontalAlignment(JLabel.CENTER); // center header text
	    
	    
	    // dimension
	   // table.setRowHeight(30);
	   // table.setFont(new Font("Serif", Font.BOLD, 20));
	    
	    ToolTipHeader header = new ToolTipHeader(table.getColumnModel());
	    header.setToolTipStrings(toolTipStr);
	    //header.setToolTipText("Default ToolTip TEXT");
	    table.setTableHeader(header);
		
		table.setDragEnabled(false);
		table.getTableHeader().setReorderingAllowed(false);
		
		TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
	    table.setRowSorter(sorter);
		
		JScrollPane scrollPane = new JScrollPane(table);
		scrollPane.setBounds(38, 11, 716, 252);
		
		
		final TableColumn booleanColumn = table.getTableHeader().getColumnModel().getColumn(BOOLEAN_COLUMN_INDEX);

		 
		// Création de la checkBox qui sera affichée en en-tête de colonne.
		final JCheckBox checkBoxHeader = new JCheckBox();

		checkBoxHeader.setSelected(true);
		// Création et affectation du cell renderer qui aura en charge la représentation de l'en-tête de colonne
		// (affichant une checkbox en plus du rendu par défaut)
		booleanColumn.setHeaderRenderer(new CheckBoxHeaderRenderer(checkBoxHeader));

		// Ajout du "forwarder". Listener qui va être informé des clics sue l'en-tête de colonne et les transmettre à la
		// checkbox.
		final HeaderMouseEventsForwarder eventFrowarder = new HeaderMouseEventsForwarder(checkBoxHeader, BOOLEAN_COLUMN_INDEX);
 		table.getTableHeader().addMouseListener(eventFrowarder);

		// Ajout du listener qui va cocher/décocher toutes les checkbox
		checkBoxHeader.addActionListener(new ActionListener() 
		{
			@Override
			public void actionPerformed(final ActionEvent e) 
			{
				if (!(e.getSource() instanceof JCheckBox)) 
				{
					return;
				}
				
				final boolean selected = ((JCheckBox) e.getSource()).isSelected();
				final TableModel model = table.getModel();
			
				for (int i = 0; i < model.getRowCount(); i++) 
				{
						model.setValueAt(selected, i, BOOLEAN_COLUMN_INDEX);
				}

			}
		});
		
		
		/****************************************************/
		
		int nb_rows = model.getRowCount();  
		
		lbl_nb_rows = new JLabel();
		lbl_nb_rows.setText("Nombre d'enregistrments : " + nb_rows);
		lbl_nb_rows.setBounds(770, 300, 170, 23);
			
		lbl_filter = new JLabel();
		lbl_filter.setText("Filter :");
		lbl_filter.setBounds(650, 357, 89, 23);
		//getContentPane().add(lbl_filter);
		
		filterText = new JTextField();
		filterText.setBounds(770, 357, 89, 23);
		//getContentPane().add(filterText);
			 
		
		filterText.getDocument().addDocumentListener(new DocumentListener() 
		{
				  public void changedUpdate(DocumentEvent e) 
				  {
					  System.out.println("update");
					  String text = filterText.getText();
					  
					  if (text.length() == 0) 
					  {
						  sorter.setRowFilter(null);
					  } 
					  else 
					  {
					  	 sorter.setRowFilter(RowFilter.regexFilter(text));
					  }
				  }

				  public void removeUpdate(DocumentEvent e) 
				  {
					  System.out.println("remove");
					  String text = filterText.getText();

					  if (text.length() == 0) 
					  {
						  sorter.setRowFilter(null);
					  } 
					  else 
					  {
						  sorter.setRowFilter(RowFilter.regexFilter(text));
					  }
				  }

				  public void insertUpdate(DocumentEvent e) 
				  {
					  System.out.println("insert");
					  
					  String text = filterText.getText();
					  if (text.length() == 0) 
					  {
						  sorter.setRowFilter(null);
					  } 
					  else 
					  {
						  sorter.setRowFilter(RowFilter.regexFilter(text));
					  }
				  }
				 
		});
		
	    /***************************************************************************/
		
		JScrollPane scrollPane_tree = new JScrollPane(tree_plan);
		scrollPane_tree.setBounds(20, 10, 220, 350);
		
		model_load_datas = new TreeModelPlanObj();
		// on charge seulement le node principal
		model_load_datas.load(flag_load_datas, tree_datas, intermediaire);
		flag_load_datas = !flag_load_datas;
	    tree_plan = new JTree(model_load_datas);

		
	    tree_plan.setComponentPopupMenu(new JTreePlanPopupMenu(intermediaire, mouse_click));
		
	    scrollPane_tree.setViewportView(tree_plan);
		 
		tree_plan.addMouseListener(new MouseAdapter() 
		{
		      public void mouseClicked(MouseEvent me) 
		      {
		    	  doMouseClicked(me);
		      }
	    });
		
		/*****************************/
/*		
		String[] column_Names =  {"Test", "Deux" , "rien"};
	     
		  
	    Object[][] row_data = {	{ "", "", ""}  };
	    
		//tableModel = new DefaultTableModel(data, columnNames)
	    modelzzz = new DefaultTableModel(row_data, column_Names)
		{
	        @Override
	        public boolean isCellEditable(int row, int column)
	        {
	            // make read only fields except column 0,13,14
	            return column == 1 || column == 2 ;
	        }
	    };
		
	    //table = new JTable(tableModel);
	    
	    table_plan = new JTable(modelzzz);
	    
	    JScrollPane scrollPane_table = new JScrollPane(table_plan);
	    scrollPane_table.setBounds(370, 70, 343, 100);
	    
	    table_plan.setRowHeight(30);
	    table_plan.setFont(new Font("Serif", Font.BOLD, 20));
	    
	    table_plan.getColumn("Deux").setCellRenderer(new TextAreaRenderer());
	    table_plan.getColumn("Deux").setCellEditor(new TextAreaEditor());
	    
	    table_plan.setRowHeight(80);			
        
	    table_plan.getColumnModel().getColumn(0).setPreferredWidth(27);
	    table_plan.getColumnModel().getColumn(1).setPreferredWidth(120);
	    table_plan.getColumnModel().getColumn(2).setPreferredWidth(100);
		
	    table_plan.setEnabled(false);
	    
	    //TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
	    //table_plan.setRowSorter(sorter);
    
	    table_plan.addFocusListener(new FocusAdapter() 
	    {
	        @Override
	        public void focusLost(FocusEvent e) 
	        {
	            //if (e.getOppositeComponent().getParent() != table) 
	            //{
	               // loseCellFocus();
	        	
	        	 
	        	 // perte du focus provoque la fin du mode edition de la cellule selecionnée
	        	 table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
	        	
	            	System.out.println("Lost focus");
	            	
	            	
	            	String retour = table.getValueAt(0, 0).toString();
	            	
	            	//int row = table.getSelectedRow();
	            	String test_str = table.getModel().getValueAt(0, 0).toString();
	            	String descrition_str = table.getModel().getValueAt(0, 1).toString();
	            	String rien_str = table.getModel().getValueAt(0, 2).toString();
	            	
	            	System.out.println(test_str + " " + descrition_str + " " + rien_str );
	            	
	            	TestPlan obj = intermediaire.GetSequenceNamed(test_str);
	            	
	            	obj.setTextchamp1(descrition_str);
	            	obj.setTextchamp2(rien_str);
	            	
	            	
	        }
	    });

	*/    
		/*****************************/
	    
	    JScrollPane scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(250, 10, 650, 130);
		
		
		String[] col =  {"AAA", "BBB" , "CCC"};
	     
		  
	    Object[][] row = {	{ "", "", ""}  };
	    
		modelbis = new DefaultTableModel(row, col)
		{
	        @Override
	        public boolean isCellEditable(int row, int column)
	        {
	            // make read only fields except column 0,13,14
	            return column == 1 || column == 2 ;
	        }
	    };
		
	    
		table_plan = new JTable(modelbis);
	    
		table_plan.setRowHeight(30);
		table_plan.setFont(new Font("Serif", Font.BOLD, 20));
	    
		table_plan.getColumn("BBB").setCellRenderer(new TextAreaRenderer());
		table_plan.getColumn("BBB").setCellEditor(new TextAreaEditor());
	    
		table_plan.setRowHeight(80);			
        
		table_plan.getColumnModel().getColumn(0).setPreferredWidth(27);
		table_plan.getColumnModel().getColumn(1).setPreferredWidth(120);
		table_plan.getColumnModel().getColumn(2).setPreferredWidth(100);
		
		table_plan.setEnabled(false);
	    
	    //TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(modelbis);
	    //table_plan.setRowSorter(sorter);
    
		table_plan.addFocusListener(new FocusAdapter() 
	    {
	        @Override
	        public void focusLost(FocusEvent e) 
	        {
	            //if (e.getOppositeComponent().getParent() != table) 
	            //{
	               // loseCellFocus();
	        	
	        	 
	        	 // perte du focus provoque la fin du mode edition de la cellule selecionnée
	        	 table_plan.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
	        	
	            	System.out.println("Lost focus");
	            	
	            	
	            	String retour = table.getValueAt(0, 0).toString();
	            	
	            	//int row = table.getSelectedRow();
	            	String test_str = table_plan.getModel().getValueAt(0, 0).toString();
	            	String descrition_str = table_plan.getModel().getValueAt(0, 1).toString();
	            	String rien_str = table_plan.getModel().getValueAt(0, 2).toString();
	            	
	            	System.out.println(test_str + " " + descrition_str + " " + rien_str );
	            	
	            	TestPlan obj = intermediaire.GetSequenceNamed(test_str);
	            	
	            	obj.setTextchamp1(descrition_str);
	            	obj.setTextchamp2(rien_str);
	            	
	            	
	        }
	    });

		
		scrollPane_1.setViewportView(table_plan);
	    
		/*****************************/
		
		String infos[][]={ {"101","Amit","670000"},    
                   			{"102","Jai","780000"},    
                   			{"101","Sachin","700000"}};    
			
		String column[]={"ID","NAME","SALARY"};         
		JTable jt=new JTable(data,column);    
		
		  JTableHeader xTheader = jt.getTableHeader();
	        
	        xTheader.setBackground(Color.red); // change the Background color
	        xTheader.setForeground(Color.WHITE); // change the Foreground
	        
	        xTheader.setFont(new Font("Tahome", Font.BOLD, 20)); // font name style size
	        ((DefaultTableCellRenderer)xTheader.getDefaultRenderer())
	                .setHorizontalAlignment(JLabel.CENTER); // center header text
			
		jt.setDragEnabled(false);
		jt.getTableHeader().setReorderingAllowed(false);
			
		jt.setBounds(30,40,200,300);          
		JScrollPane sp=new JScrollPane(jt);   
		
		/*****************************/
		
		
		TABLE_MODEL mod = new TABLE_MODEL();
        JTable table_progress = new JTable(mod);
        
        table_progress.setRowHeight(30);
        table_progress.setFont(new Font("Serif", Font.BOLD, 20));
        
        mod.addRow("dctr1.doc");
        mod.addRow("java.txt");
        mod.addRow("dctr3.doc");
        mod.addRow("dctr4.doc");
        mod.addRow("dctr5.doc");
        
        UIManager.put("ProgressBar.selectionForeground", Color.red);
        UIManager.put("ProgressBar.selectionBackground", Color.green);
        
//        scrollPane.setViewportView(table);
        
        table_progress.getColumnModel().getColumn(0).setCellRenderer(new CELL_RENDERER());
        table_progress.getColumnModel().getColumn(0).setCellEditor(new TableCellEditor() {
            @Override
            public boolean stopCellEditing() {
                return false;
            }
            @Override
            public boolean shouldSelectCell(EventObject arg0) {
                return false;
            }
            @Override
            public void removeCellEditorListener(CellEditorListener arg0) {}
            @Override
            public boolean isCellEditable(EventObject arg0) {
                 return false;
            }
            @Override
            public Object getCellEditorValue() {
                return null;
            }
            @Override
            public void cancelCellEditing() {}
            @Override
            public void addCellEditorListener(CellEditorListener arg0) {    }   
            @Override
            public Component getTableCellEditorComponent(JTable table, Object value,
                    boolean isSelected, int row, int column) {
                return null;
            }
        });
     
        JProgressBar progressBar1=(JProgressBar)table_progress.getValueAt(0, 0);
        progressBar1.setStringPainted(true);
        progressBar1.setBorderPainted(false);
        progressBar1.setValue(10);
        table_progress.repaint();
        
        JProgressBar progressBar2=(JProgressBar)table_progress.getValueAt(1, 0);
        progressBar2.setStringPainted(true);
        progressBar2.setBorderPainted(false);
        progressBar2.setValue(45);
        table_progress.repaint();
        
        JProgressBar progressBar3=(JProgressBar)table_progress.getValueAt(2, 0);
        progressBar3.setStringPainted(true);
        progressBar3.setValue(25);
        progressBar3.setBorderPainted(false);
        table_progress.repaint();
        
        JProgressBar progressBar4=(JProgressBar)table_progress.getValueAt(3, 0);
        progressBar4.setStringPainted(true);
        progressBar4.setBorderPainted(false);
        progressBar4.setValue(98);
        table_progress.repaint();
        
        JScrollPane scrollPane_2 = new JScrollPane(table_progress);
		scrollPane_2.setBounds(38, 11, 716, 252);
		
		/****************************/
		
		
		JPanel panel = new JPanel();
		tabbedPane.addTab("New tab", null, panel, null);
		panel.setLayout(null);
		panel.add(scrollPane);
		
		panel.add(lbl_nb_rows);
		
		panel.add(lbl_filter);
		panel.add(filterText);
		
		//panel.setLayout(null);
		
		JPanel panel_1 = new JPanel();
		tabbedPane.addTab("Chichi", null, panel_1, null);
		panel.setLayout(null);
		panel_1.add(sp);
		
		//JPanel panel_2 = new JPanel();
		//tabbedPane.addTab("New tab", null, panel_2, null);
		//panel_2.setLayout(null);
		//panel_2.add(scrollPane_tree);
		
		JPanel panel_2 = new JPanel();
		tabbedPane.addTab("New tab", null, panel_2, null);
		panel_2.setLayout(null);
		panel_2.add(scrollPane_tree);
		//panel_2.add(scrollPane_table);
		panel_2.add(scrollPane_1);

		
		
	/*	JButton btn_load_tree  = new JButton("Load");
		btn_load_tree.setBounds(50, 750, 89, 23);
		panel_2.add(btn_load_tree);
		
		JButton btn_save_tree = new JButton("Save");
	    btn_save_tree.setBounds(700, 750, 89, 23);
		panel_2.add(btn_save_tree);
	*/    
	    
		JButton btn_load_tree = new JButton("Load");
		btn_load_tree.setBounds(34, 380, 89, 23);
		panel_2.add(btn_load_tree);
			
		JButton btn_save_tree = new JButton("Save");
		btn_save_tree.setBounds(134, 380, 89, 23);
		panel_2.add(btn_save_tree);
	
		
	 /*   JButton btnNewButton_1 = new JButton("zobi");
		btnNewButton_1.setBounds(334, 380, 89, 23);
		panel_2.add(btnNewButton_1);
		
		JButton btnNewButton_2 = new JButton("lulu");
		btnNewButton_2.setBounds(534, 380, 89, 23);
		panel_2.add(btnNewButton_2);
	    
		JButton btnNewButton_3 = new JButton("w");
		btnNewButton_3.setBounds(734, 380, 89, 23);
		panel_2.add(btnNewButton_3);*/
	
		
		/*****************************/
		
		JPanel panel_3 = new JPanel();
		tabbedPane.addTab("New tab", null, panel_3, null);
		
		JButton btnNewButton = new JButton("New button");
		btnNewButton.setBounds(76, 93, 89, 23);
		panel_3.add(btnNewButton);
		
		panel_3.add(scrollPane_2);
		
		/*****************************/
		
		getContentPane().setLayout(null);
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setToolTipText("mlm\u00F9l");
			buttonPane.setBounds(0, 579, 984, 33);
			buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER));
			getContentPane().add(buttonPane);
			{
				JButton okButton = new JButton("OK");
				okButton.setActionCommand("OK");
				okButton.addActionListener(new ActionListener() 
				{
					public void actionPerformed(ActionEvent arg0) 
					{
						System.out.println("Ok  \n");
						dispose(); 
				        setVisible(false);
					}
				});
				
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton cancelButton = new JButton("Cancel");
				cancelButton.setActionCommand("Cancel");
				cancelButton.addActionListener(new ActionListener() 
				{
					public void actionPerformed(ActionEvent arg0) 
					{
						System.out.println("Close  \n");
						dispose(); 
				        setVisible(false);
					}
				});

				buttonPane.add(cancelButton);
			}
		}
		
		/*******************/
	
		btn_load_tree.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent arg0) 
			{
				System.out.println("Btn load  \n");
				loadJtree();
			}
		});
		//btn_load_tree.setBounds(50, 650, 89, 23);
		//getContentPane().add(btn_load_tree);
		
	    /*******************/
		
		btn_save_tree.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent arg0) 
			{
				System.out.println("Btn save  \n");
		        TreeModel model = tree_plan.getModel(); 
				saveJtree(model);
			}
		});
		//btn_save_tree.setBounds(161, 650, 89, 23);
		//getContentPane().add(btn_save_tree);

		
	    
	}	
	
	/****************************************************************************************/
	
	 public void actionPerformed(ActionEvent eve)
	    {
	        if(eve.getActionCommand() == "okButton")
	            JOptionPane.showMessageDialog(rootPane, "JButton01 Pressed");
	        else if(eve.getActionCommand() == "jb2")
	            JOptionPane.showMessageDialog(rootPane, "JButton02 Pressed");
	        else if(eve.getActionCommand() == "jb3")
	            JOptionPane.showMessageDialog(rootPane, "JButton03 Pressed");
	    } 
	
	
	public ImageIcon createImageIcon(String path,  String description) 
	{
		URL imgURL = getClass().getResource(path);

		if (imgURL != null)
		{
  			return new ImageIcon(imgURL, description);
		} 
		else 
		{
			System.err.println("Couldn't find file: " + path);
			return null;
		}
	}
	
	class ToolTipHeader extends JTableHeader 
	{
		String[] toolTips;
	   
	    public ToolTipHeader(TableColumnModel model) 
	    {
	    	super(model);
	    }
	     
	    public String getToolTipText(MouseEvent e) 
	    {
	      int col  = columnAtPoint(e.getPoint());
	      int modelCol = getTable().convertColumnIndexToModel(col);
	      String retStr;
	    
	      try 
	      {
	    	  retStr = toolTips[modelCol];
	      } 
	      catch (NullPointerException ex) 
	      {
	        retStr = "";
	      } 
	      catch (ArrayIndexOutOfBoundsException ex) 
	      {
	        retStr = "";
	      }
	      
	      if (retStr.length() < 1) 
	      {
	        retStr = super.getToolTipText(e);
	      }
	      return retStr;
	    }  
	     
	    public void setToolTipStrings(String[] toolTips) 
	    {
	    	this.toolTips = toolTips;
	    }
	}
	
	public void doMouseClicked(MouseEvent me) 
	{
		TreePath TreePathObj = tree_plan.getPathForLocation(me.getX(), me.getY());
		
		if(TreePathObj != null)
		{	
			Object pathString[] = TreePathObj.getPath();
		
			String value = "";
			String s = "";
			String str_concate = "";

			for (int i = 0; i < pathString.length ; i++) 
			{
				str_concate+=pathString[i] + ":";
			}	

			// nb d'ocuurence *
			int nb_occurence = str_concate.length() - str_concate.replace(":", "").length();
			
			System.out.println("----->  " + str_concate + " " + nb_occurence );  
			
			mouse_click = str_concate;
			
			if(nb_occurence == 3)
			{
				table_plan.setEnabled(true);

				// enlever le dernier caractere du path 
				String str_tmp = str_concate.substring(0, str_concate.length()-1); 
				// decoupe
				String[] parts = str_tmp.split(":");
				
				System.out.println(" Selection children " + parts[2] );   
				//tableModel.setValueAt(parts[2], 0, 0);
				modelbis.setValueAt(parts[2], 0, 0);
				
				//System.out.println(" Selection children " + parts[1]);   
				TestPlan obj = intermediaire.GetSequenceNamed(parts[2]);
				String val1 = obj.getTextchamp1();
	        	String val2 = obj.getTextchamp2();
				//tableModel.setValueAt(val1, 0, 1);
				//tableModel.setValueAt(val2, 0, 2);
	        	modelbis.setValueAt(val1, 0, 1);
	        	modelbis.setValueAt(val2, 0, 2);

				
				
			}
			
			else
			{
				//int[] selected_row = table.getSelectedRows();
				//if( selected_row.length != 0 ) //&& nb_occurence == 3)
				//{	
				//	System.out.println("TRACE");
				//	table.getCellEditor().stopCellEditing();
				//}
				
				//tableModel.setValueAt("", 0, 0);
				//tableModel.setValueAt("", 0, 1);
				//tableModel.setValueAt("", 0, 2);
				modelbis.setValueAt("", 0, 0);
				modelbis.setValueAt("", 0, 1);
				modelbis.setValueAt("", 0, 2);
				table_plan.setEnabled(false);
				
			}
		
		}
		else
		{
			System.out.println(" Jtree area ");   
		}
 	
	}
	
	
	public  ArrayList<String> explore_tree(TreeModel model)
    {
    	 Object alpha = model.getRoot();
         String root_str = alpha.toString();
         System.out.println(root_str);
         
         ArrayList<String> array = new ArrayList<String>();
         
         for(int i = 0; i < ((DefaultMutableTreeNode) alpha).getChildCount() ; i++) 
         {
             DefaultMutableTreeNode child = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) alpha).getChildAt(i);
             String noeud = child.getUserObject().toString();
             //System.out.println(noeud);
             array.add(noeud);
             
             for(int j = 0; j < child.getChildCount() ; j++) 
             {
                 DefaultMutableTreeNode aaachild = (DefaultMutableTreeNode) child.getChildAt(j);
                 String sub = aaachild.getUserObject().toString();
                 TestPlan obj = intermediaire.GetSequenceNamed(sub);
 				 String val1 = obj.getTextchamp1();
 	        	 String val2 = obj.getTextchamp2();
 	        	 //System.out.println(sub + "-" + val1 + "-" + val2);
 	        	 array.add(sub + "-" + val1 + "-" + val2);
             }
         }
         
         return(array);
    }
	
	private void loadJtree() 
	{
	    	 JFileChooser chooser = new JFileChooser();
	    	 chooser.setDialogTitle("Choice XML file");
	    	 FileNameExtensionFilter filter = new FileNameExtensionFilter( "XML file", "xml" );
	    	 chooser.setFileFilter(filter);
	    	 
	    	 int returnVal = chooser.showOpenDialog(this);
	
	    	 if(returnVal == JFileChooser.APPROVE_OPTION) 
	    	 {
	    	       File selectedFile = chooser.getSelectedFile();
	    	       tree_datas = READ_XML.Tree_ReadXML( selectedFile.getPath() );
	    	       model_load_datas.load(flag_load_datas, tree_datas, intermediaire);
				   flag_load_datas = !flag_load_datas;
	    	 }
	}
	   
    private void saveJtree(TreeModel model) 
	{
	    	JFileChooser fileChooser = new JFileChooser();
	    	fileChooser.setDialogTitle("Specify a file to save");   
	    	 
	    	// fileChooser.setSelectedFile(new File("myfile.xml"));
	    	fileChooser.setFileFilter(new FileNameExtensionFilter("xml file","xml"));
	    	
	    	int userSelection = fileChooser.showSaveDialog(this);
	    	 
	    	if (userSelection == JFileChooser.APPROVE_OPTION) 
	    	{
	    	    File fileToSave = fileChooser.getSelectedFile();
	    	    System.out.println("Save as file: " + fileToSave.getAbsolutePath());
	    	    
	    	    // collecte les datas
	    	    
	    	    tmp_tree_datas.clear();
	    	    tmp_tree_datas = explore_tree(model);
	    	    
	    	    /*ArrayList<TestPlan>  objTree  = new ArrayList<TestPlan>();
			    objTree = intermediaire.getTreeChild();

	            for(int i = 0; i < objTree.size(); i++)
	            {
	            	String type = objTree.get(i).getType();
	            	String sequence = objTree.get(i).getSequence();
					String val1 = objTree.get(i).getTextchamp1();
		        	String val2 = objTree.get(i).getTextchamp2();
		        	if(val1.equals("") && val2.equals("") )
		        	{
		        		tmp_tree_datas.add(sequence);
		        	}
		        	else
		        	{	
		        		tmp_tree_datas.add(sequence + "-" + val1 + "-" + val2);
		        	}
		        	System.out.println(" DATA collection to save in file: " + type + "-" + val1 + "-" + val2);
	            }*/
	    	    
	    	    WRITE_XML.Tree_WirteXML(tmp_tree_datas, fileToSave.getAbsolutePath());
	    	    
	    	}
	    	
	}
    
	
	
}

/***********************************************************************************************/

class JTreePlanPopupMenu extends JPopupMenu 
{
	  protected TreePath path;

	  int NODE_MAXIMUM_LEVELS = 2;
	  
	 // Class_plan intermediaire = new Class_plan();

	  int level = 0;
	  int sublevel = 0;
	  
	  protected JTreePlanPopupMenu(Class_plan intermediaire, String mouse_click) 
	  {
	    super();

	     // intermediaire.addSequence(new TestPlan());
	    
	    add("add child node").addActionListener(e -> 
	    {
	    		JTree tree = (JTree) getInvoker();
	    		TreePath path = tree.getSelectionPath();
	    	
	    		if(path != null )
	    		{
	    			if (path.getPathCount() <= NODE_MAXIMUM_LEVELS) 
	    			{
			    		  DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
			    		  DefaultMutableTreeNode self = (DefaultMutableTreeNode) path.getLastPathComponent();
			    		  DefaultMutableTreeNode child = new DefaultMutableTreeNode("New child node");
			    		  self.add(child);
			    		  model.reload(self);
			  
			    		  Object pathString[] = path.getPath();
			    		  int n = pathString.length;
			    		  String type = "";
		    		  		    		  
			    		  switch(n) 
			    		  {
				             case 1 :
				            	 		type = "test";
				            	 		level = level + 1;
				            	 		System.out.println(" [Infos]:  level ---> " + type + " " + level);
				            	 		break;
				             case 2 :
				            	 		type = "subtest";
				            	 		sublevel = sublevel + 1;
				            	 		 System.out.println(" [Infos]:  ---> " + type + " " + sublevel);
				            	 		break;
				             default :
				            	 		System.out.println("Invalid choice");
			    		  }
			    			
			    		  intermediaire.addSequence(new TestPlan(type, level, "New child node", "", "") );
			    		  //System.out.println(" [Infos]:  ---> " + type + " " + level);
		    		  
		    	  }
		    	  else 
			      {
			    	  String message = String.format("ERROR: Maximum levels of %d exceeded.", NODE_MAXIMUM_LEVELS);
			          JOptionPane.showMessageDialog(tree, message, "add node", JOptionPane.ERROR_MESSAGE);
			      }
		    	  
		      }
		      else
		      {
		    	  String message = String.format("ERROR: Please , select tree node !. ");
		 	      JOptionPane.showMessageDialog(tree, message, "add child node", JOptionPane.ERROR_MESSAGE);
		      }
		      
	    });
	    
	    addSeparator();
	    
	    add("insert preceding sibling node").addActionListener(e -> 
	    {
	    	if( mouse_click.equals("Plan"))
	    	{
	    		JTree tree = (JTree) getInvoker();
	    		DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
	    		DefaultMutableTreeNode self = (DefaultMutableTreeNode) path.getLastPathComponent();
	    		DefaultMutableTreeNode parent = (DefaultMutableTreeNode) self.getParent();
	    		DefaultMutableTreeNode child = new DefaultMutableTreeNode("New preceding sibling");
	    		int index = model.getIndexOfChild(parent, self);
	    		parent.insert(child, index);
	    		model.reload(parent);
	    	}
	    	else
	    	{
		    	  String message = String.format("You can not add node at root level !.");
		          JOptionPane.showMessageDialog(this, message, "Warning", JOptionPane.ERROR_MESSAGE);

	    	}
	      // or: model.insertNodeInto(child, parent, index);
	    });
	    
	    add("insert following sibling node").addActionListener(e -> 
	    {
	    	if( mouse_click.equals("Plan"))
	    	{
			    JTree tree = (JTree) getInvoker();
			    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
			    DefaultMutableTreeNode self = (DefaultMutableTreeNode) path.getLastPathComponent();
			    DefaultMutableTreeNode parent = (DefaultMutableTreeNode) self.getParent();
			    DefaultMutableTreeNode child = new DefaultMutableTreeNode("New following sibling");
			    int index = model.getIndexOfChild(parent, self);
			    parent.insert(child, index + 1);
			    model.reload(parent);
			    // or: model.insertNodeInto(child, parent, index + 1);
			}
	    	else
	    	{
		    	  String message = String.format("You can not add node at root level !.");
		          JOptionPane.showMessageDialog(this, message, "Warning", JOptionPane.ERROR_MESSAGE);
	    	}
	    });
	    
	    
	    add("Remove").addActionListener(e -> 
	    {
	    	DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
		    if (!node.isRoot()) 
		    {
		    	  
		    	int response = JOptionPane.showConfirmDialog(null, "Do you want to delete this item ?", "Confirm",
		    					JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
		    	
		    	if (response == JOptionPane.NO_OPTION) 
		    	{
		    		System.out.println("No button clicked");
		    	} 
		    	else if (response == JOptionPane.YES_OPTION) 
		    	{
		    		System.out.println("Yes button clicked");
		    		JTree tree = (JTree) getInvoker();
		  		    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
		  		    model.removeNodeFromParent(node);
		    	} 
		    	else if (response == JOptionPane.CLOSED_OPTION) 
		    	{
		    		System.out.println("JOptionPane closed");
		    	}  
	      
		    }
	    });
		    
	    add("Edit").addActionListener(e -> 
	    {
	    	JTextField textField = new JTextField(); //24
	    	Object node = path.getLastPathComponent();
		      
	    	DefaultMutableTreeNode leaf = (DefaultMutableTreeNode) node;
	    	textField.setText(leaf.getUserObject().toString());
	    	JTree tree = (JTree) getInvoker();
	        
	    	if( !textField.getText().equals("Plan"))
	    	{	
		    	int ret = JOptionPane.showConfirmDialog(tree, textField, "edit", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
		    	if (ret == JOptionPane.OK_OPTION) 
		    	{
		    		Optional.ofNullable(textField.getText())
		            .filter(str -> !str.trim().isEmpty())
		            .ifPresent(str -> {
		              DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
		              String old_sequence = leaf.getUserObject().toString();
		              model.valueForPathChanged(path, str);

		              // mise à jour de la database
		             
		              TestPlan obj = intermediaire.GetSequenceNamed(old_sequence);
		              obj.setSequence(str); 
		              
		            });
		    	}
	    	}
	    	 else 
		     {
		    	  String message = String.format("ERROR: Plan level cannot be changed !.", NODE_MAXIMUM_LEVELS);
		          JOptionPane.showMessageDialog(tree, message, "Edit node", JOptionPane.ERROR_MESSAGE);
		      }
	    });
	    
	  }

	  @Override 
	  public void show(Component c, int x, int y) 
	  {
	    if (c instanceof JTree) 
	    {
	    	JTree tree = (JTree) c;
	    	path = tree.getPathForLocation(x, y);
	    	Optional.ofNullable(path).ifPresent(tp -> super.show(c, x, y));
	    }
	  }

}


/***********************************************************************************************/

class TreeModelPlanObj extends DefaultTreeModel 
{

	  DefaultMutableTreeNode root = null;  // declaration en debut de fichier

	  public TreeModelPlanObj() 
	  {
		  super(new DefaultMutableTreeNode("Plan"));
		  root = (DefaultMutableTreeNode) getRoot();
	  }

	  public void load(boolean flag_load, ArrayList<String> datas, Class_plan intermediaire ) 
	  {
		  root.removeAllChildren();
		  
		  if (flag_load)
		  {	
			  DefaultMutableTreeNode treeObj = null;
			
			  for(int i = 0 ; i < datas.size() ; i++)
			  {
				  boolean retval = datas.get(i).contains("-");
				  if(retval == false )
				  {
					  treeObj = new DefaultMutableTreeNode( datas.get(i) );
					  root.add(treeObj);
					  intermediaire.addSequence(new TestPlan("test", 1, datas.get(i), "", "") );
				  }
				  else
				  {
					  String[] parts = datas.get(i).split("-");
					  treeObj.add(new DefaultMutableTreeNode( parts[0] ));
					  intermediaire.addSequence(new TestPlan("subtest", 1, parts[0], parts[1], parts[2]) );
				  }
			  }
		
			  nodeStructureChanged(root);
		  }
	  }

	  public TreeNode getRootNode() 
	  {
		  return root;
	  }
}


// http://covered.sourceforge.net/

// https://stackoverflow.com/questions/9499533/how-to-make-a-jxtreetable-sort-its-top-elements