package fr.umlv.uidemo;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.net.URL;

import javax.swing.*;
import javax.swing.event.*;

/**
 * @author Remi Forax
 *
 */
public class ActionExample {

  private Icon getIcon(String iconFileName) {
    URL url=getClass().getResource(iconFileName);
    if (url==null)
      return null;
      
    return new ImageIcon(url);
  }
  
  private JToolBar createToolBar(Action[] actions) {
    JToolBar bar=new JToolBar();
    for(int i=0;i<actions.length;i++)   
      bar.add(new JButton(actions[i]));
    return bar;
  }
  
  private JMenu createMenu(String title,Action[] actions) {
    JMenu menu=new JMenu(title);
    for(int i=0;i<actions.length;i++)   
      menu.add(new JMenuItem(actions[i]));
    return menu;
  }
  
  private JFrame createFrame(String title) {
    final JTextArea area=new JTextArea();
    
    final Action cutAction=new AbstractAction("cut",getIcon("Cut24.gif")) {
      public void actionPerformed(ActionEvent e) {
        area.cut();
      }
    };
    cutAction.putValue(Action.SHORT_DESCRIPTION, "couper");
    cutAction.setEnabled(false);
    
    Action pasteAction=new AbstractAction("paste",getIcon("Paste24.gif")) {
      public void actionPerformed(ActionEvent e) {
        area.paste();
      }
    };
    
    area.addCaretListener(new CaretListener() {
      public void caretUpdate(CaretEvent e) {
        String text=area.getSelectedText();
        cutAction.setEnabled(text!=null);
      }
    });
    
    Action[] actions=new Action[] {
      cutAction,pasteAction
    };
    
    JFrame frame=new JFrame(title);
    JMenuBar menuBar=new JMenuBar();
    menuBar.add(createMenu("Edit",actions));
    frame.setJMenuBar(menuBar);
    
    Container c=frame.getContentPane();
    c.add(createToolBar(actions),BorderLayout.NORTH);
    c.add(area);
      
    return frame;
  }

  public static void main(String[] args) {
    
    ActionExample example=new ActionExample();
    
    JFrame frame=example.createFrame("ActionExample");
    frame.setSize(400,300);
    frame.show();
  }
}
