

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JSeparator;
import javax.swing.JTable;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.imageio.ImageIO;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;


import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;

// http://tecfa.unige.ch/guides/tie/pdf/files/java-swing.pdf
// http://myflex.org/yf/java/slides/Unit13.pdf    

// MVC  JTABLE

public class Dialog01 extends JDialog 
{
	
	private boolean close_Jdialog = false;
	
	
	private JTextField textField_1;
	private JTextField textField_2;
	private JTextField textField_3;
	
	public Dialog01(JFrame f, boolean modal) 
	{
       super(f, modal);
       
       //Point location = f.getLocation();
       //setLocation(location.x + 250, location.y + 750);

       // fermer la fenetre
       addWindowListener(new java.awt.event.WindowAdapter() 
       {
           public void windowClosing(java.awt.event.WindowEvent e) 
           {
        	   dispose();
           }
       });
       
       //init();
       //aaa();
       bbb();
	}

	// envoi les datas
	public void initialise( Object [] o)
	{
		
	}
 
	// retourne les datas
	public Object [] getDonnees()
	{
		return null;
	
	}
  
	private void init()
	{
	  	setResizable( false );
	  	setBounds(100, 100, 600, 460);
		getContentPane().setLayout(null);
     	
		ImageIcon icon = null;
		icon = createImageIcon("resources/settings.png", "");
		setIconImage( icon.getImage() );
		
		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
		setTitle("Settings state parameters ");
		
		JTable table = new JTable(); 
        Object[] columns = {"Id","First Name","Last Name","Age"};
        DefaultTableModel model = new DefaultTableModel();
        model.setColumnIdentifiers(columns);
        
        // set the model to the table
        table.setModel(model);
        
        table.setBackground(Color.LIGHT_GRAY);
        table.setForeground(Color.black);
        //Font font = new Font("",1,22);
        //table.setFont(font);
        //table.setRowHeight(30);
		
        JScrollPane pane = new JScrollPane(table);
        pane.setBounds(34, 24, 525, 180);
        getContentPane().add(pane);
        
        JComboBox combo = new JComboBox();
        combo.addItem("No");
        combo.addItem("Yes");
        combo.addItem("blabla");
        combo.addItem("Taratata");
        
        table.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(combo));
        
        
        Object[] row = new Object[4];
        
		JButton btn_addrow = new JButton("New button");
		btn_addrow.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent arg0) 
			{
				System.out.println("Btn add row ");
				
				  row[0] = "a";
	                row[1] = "b";
	               // row[2] = "c";
	                row[3] = "d";
	                
	                // add row to the model
	                model.addRow(row);
				
			
				
			}
		});
		btn_addrow.setBounds(65, 242, 89, 23);
		getContentPane().add(btn_addrow);
		
		JButton btn_remove = new JButton("Remove");
		btn_remove.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e) 
			{
	               int i = table.getSelectedRow();
	               if(i >= 0)
	               {
	                   // remove a row from jtable
	                   model.removeRow(i);
	               }
				
			}
		});
		btn_remove.setBounds(65, 276, 89, 23);
		getContentPane().add(btn_remove);
		
		
		
		/*******************/
		
		JSeparator separator = new JSeparator();
		separator.setBounds(1, 384, 600, 2);
		getContentPane().add(separator);
	
		/*******************/
		
		JButton btn_ok = new JButton("OK");
		btn_ok.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent arg0) 
			{
				close_Jdialog = false;
				System.out.println("Btn Cancel  \n");
				dispose();
			}
		});
		btn_ok.setBounds(135, 391, 89, 23);
		getContentPane().add(btn_ok);
	
		/*******************/
		
		JButton btn_cancel = new JButton("Cancel");
		btn_cancel.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e) 
			{
				Object[][] tableData = getTableData (table);
				
				model.setRowCount(0);
				
				int len = tableData.length;
				
				for (int i = 0 ; i < len ; i++)
				{
					System.out.println("Contenu :" + tableData[i][0] + " " + tableData[i][1] + "  " +  tableData[i][2] + "  " + tableData[i][3] );
					
					row[0] = tableData[i][0];
	                row[1] = tableData[i][1];
		            row[2] = tableData[i][2];
		            row[3] = tableData[i][3];
		            model.addRow(row);
				}
				
				
				close_Jdialog = false;
				System.out.println("Btn Cancel  \n");
				//dispose();
				
				
			}
		});
		btn_cancel.setBounds(359, 391, 89, 23);
		getContentPane().add(btn_cancel);
		
		/*******************/
	}
	
	public Object[][] getTableData (JTable table) 
	{
		TableModel dtm = table.getModel();
		int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
		
		Object[][] tableData = new Object[nRow][nCol];
		
		for (int i = 0 ; i < nRow ; i++)
		{	
			for (int j = 0 ; j < nCol ; j++)
		    {
				tableData[i][j] = dtm.getValueAt(i,j);
		    }
		}    
		
		return tableData;
	}
    
	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;
		}
	}
	
	
	/******************************************/
	
	private void aaa()
 	{
		
 		setResizable( false );
	  	setBounds(100, 100, 600, 460);
		getContentPane().setLayout(null);
		
		ImageIcon icon = null;
		icon = createImageIcon("resources/settings.png", "");
		setIconImage( icon.getImage() );
		
		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
		setTitle("Plouf... ");
		
		
		JTable table = new JTable(); 
        Object[] columns = {"Id","First Name","Last Name","Age"};
        DefaultTableModel model = new DefaultTableModel();
        model.setColumnIdentifiers(columns);
		
		
     // set the model to the table
        table.setModel(model);
        
        table.setBackground(Color.LIGHT_GRAY);
        table.setForeground(Color.black);
        //Font font = new Font("",1,22);
        //table.setFont(font);
        //table.setRowHeight(30);
		
        JScrollPane pane = new JScrollPane(table);
        pane.setBounds(34, 24, 525, 180);
        getContentPane().add(pane);
        
        JComboBox combo = new JComboBox();
        combo.addItem("No");
        combo.addItem("Yes");
        
        table.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(combo));
		
		/*******************/			
		
		JLabel lbl1 = new JLabel("aaaa :");
		lbl1.setBounds(36, 255, 45, 14);
		getContentPane().add(lbl1);
		
		JLabel lbl2 = new JLabel("bbbb :");
		lbl2.setBounds(36, 289, 45, 14);
		getContentPane().add(lbl2);
		
		textField_1 = new JTextField();
		textField_1.setBounds(90, 252, 86, 20);
		getContentPane().add(textField_1);
		textField_1.setColumns(10);
		
		textField_2 = new JTextField();
		textField_2.setColumns(10);
		textField_2.setBounds(90, 286, 86, 20);
		getContentPane().add(textField_2);
		
		textField_3 = new JTextField();
		textField_3.setColumns(10);
		textField_3.setBounds(90, 323, 86, 20);
		getContentPane().add(textField_3);
		
		JLabel lbl3 = new JLabel("cccc :");
		lbl3.setBounds(36, 326, 45, 14);
		getContentPane().add(lbl3);
		
		/*******************/			

		Object[] row = new Object[4];
        
		JButton btn_addrow = new JButton("Add Test");
		btn_addrow.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent arg0) 
			{
	              // add row to the model
	              row[0] = textField_1.getText();
	              row[1] = textField_2.getText();
	              // row[2] = ""
	              row[3] = textField_3.getText();
	              model.addRow(row);  
			}
		});
		btn_addrow.setBounds(441, 252, 89, 23);
		getContentPane().add(btn_addrow);
		
		JButton btn_remove = new JButton("Remove Test");
		btn_remove.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e) 
			{
	               int i = table.getSelectedRow();
	               if(i >= 0)
	               {
	                   model.removeRow(i);
	               }
			}
		});
		btn_remove.setBounds(441, 286, 89, 23);
		getContentPane().add(btn_remove);

		
		/*******************/
		
		JSeparator separator = new JSeparator();
		separator.setBounds(1, 384, 600, 2);
		getContentPane().add(separator);
	
		/*******************/
		
		JButton btn_ok = new JButton("OK");
		btn_ok.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent arg0) 
			{
			
				System.out.println("Btn OK  \n");
				dispose();
			}
		});
		btn_ok.setBounds(135, 391, 89, 23);
		getContentPane().add(btn_ok);
	
		/*******************/
		
		JButton btn_cancel = new JButton("Cancel");
		btn_cancel.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e) 
			{
				
				System.out.println("Btn Cancel  \n");
				dispose();
			}
		});
		btn_cancel.setBounds(359, 391, 89, 23);
		getContentPane().add(btn_cancel);
		
		/*******************/
		
		JButton btnUpdate = new JButton("Update");
		btnUpdate.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e) 
			{
				
				System.out.println("Btn update  \n");
				
				// retourne le contenu de la cellule
	        	String val = (String) table.getModel().getValueAt(0, 2);
	        	   
	               
	            int nb_row = table.getRowCount();
	            int nb8col = table.getColumnCount();
	               
	            String selectedData = null;
	            int[] selectedRow = table.getSelectedRows();
	            int[] selectedColumns = table.getSelectedColumns();

	              
	            // i = the index of the selected row
	            int i = table.getSelectedRow();
	               
            	if(i >= 0) 
            	{
            		model.setValueAt(textField_1.getText(), i, 0);
	                model.setValueAt(textField_2.getText(), i, 1);
	                model.setValueAt(textField_3.getText(), i, 2);
            	}
	            else
	            {
	                System.out.println("Update Error");
	            }
			}
		});
		btnUpdate.setBounds(441, 322, 89, 23);
		getContentPane().add(btnUpdate);
		
		/*******************/
		
		// get selected row data From table to textfields 
		table.addMouseListener(new MouseAdapter()
	    {
	       @Override
	       public void mouseClicked(MouseEvent e)
	       {
	           // i = the index of the selected row
	           int i = table.getSelectedRow();
	           
	           textField_1.setText(model.getValueAt(i, 0).toString());
	           textField_2.setText(model.getValueAt(i, 1).toString());
	          // textLname.setText(model.getValueAt(i, 2).toString());
	           textField_3.setText(model.getValueAt(i, 3).toString());
	       }
	    });
		
		
 	}
	
	private void bbb()
	{
		DefaultTableModel dtm = new DefaultTableModel() 
		{
		       // make first cell uneditable
		       public boolean isCellEditable(int row, int column)
		       {
		          return !(column == 0);
		       }
		    };
		    
			
		  
		
			
		    dtm.setDataVector(new Object[][]{{ "JTextArea1", "This is a testnon long linesn" },
		                                     { "JTextArea2", "Hello, world!" }},
		                      new Object[]{ "String","JTextArea"});
		                      
		    JTable table = new JTable(dtm);
		    table.getColumn("JTextArea").setCellRenderer(new TextAreaRenderer());
		    table.getColumn("JTextArea").setCellEditor(new TextAreaEditor());
		  
		    table.setRowHeight(80);
		    JScrollPane scroll = new JScrollPane(table);
		    getContentPane().add(scroll);
		  
		    
			  setSize( 400, 250 );
			    setVisible(true);
	}
	
	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();
	   }
	} 
  
}