SlideShare una empresa de Scribd logo
1 de 10
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;



public class Edit extends JFrame {
     //Inicializacion del tama ño de la fuente
     int tama ño=20;

     //Para explorar directorios para abrir y guardar archivos
     JFileChooser fileChooser = null;
     //Para escribir texto
     JEditorPane editPane;
     //Scroll del lado derecho
     JScrollPane scrollPaneRight;
     //Scroll del lado izquierdo
     JScrollPane scrollPaneLeft;
     //Panel izquierdo donde va la lista de archivo abiertos
     JPanel leftPanel;
     //La barra del Menu
     JMenuBar menuBar;
     //El menu
     JMenu MArchivo;
     JMenu MEdicion;
     //Los items del menu
     JMenuItem MNuevo;
     JMenuItem MAbrir;
     JMenuItem MGuardar;
     JMenuItem MSalir;
     JMenuItem MImprimir;
     JMenuItem MCortar;
     JMenuItem MPegar;
     JMenuItem MBuscar;
     JMenuItem MCopiar;
     JMenuItem Fuente;
     //Contenedor con division izquierda derecha
     JSplitPane splitPane;
     //El panel del estado y sus mensajes
     JPanel statusPanel;
     JLabel statusMsg1;
     JLabel statusMsg2;
     //Tool bar
     JToolBar toolBar;
     //Todos los botones
     JButton BCortar;
     JButton BAbrir;
     JButton BGuardar;
     JButton BCopiar;
     JButton BPegar;
     JButton BNuevo;
JButton BImprimir;
     JButton openSelectedButton;
     private JComboBox tFuente;
     private Font areaFuente;
     private JScrollPane scroll;

     //cajas de texto
     JTextArea Texto = new JTextArea();

     JTextArea Errores=new JTextArea(6,1);

     String Copiar="";
     //La lista que se despliega en el lado izquierdo
     JList list;
     //Vector para almacenar los archivos abiertos
     Vector fileVector = new Vector();
     String fileName;
     boolean isSaved = false;

     //Clase interna para manejar los eventos
     class EventHandler implements ActionListener
     {
           public void actionPerformed(ActionEvent e)
           {
                 //Si se elige salir en el menu
                 if (e.getSource() == MSalir)
                 {
                        //Si el archivo abierto no esta en blanco y no esta guardado
                        if (!isSaved && !editPane.getText().equals(""))
                               askSave();
                        System.exit(0);
                 }
                 //Si se elige abrir un archivo en el menu o con el boton de abrir en el
toolbar
                 if (e.getSource() == MAbrir || e.getSource() == BAbrir)
                 {
                        //misma verificacion anterior
                        if (!isSaved && !editPane.getText().equals(""))
                               askSave();
                        openFile();
                 }
                 //Si se elige en el menu editar un archivo en blanco
                 if (e.getSource() == MNuevo)

                {
                      //idem
                      if (!isSaved && !editPane.getText().equals(""))
                             askSave();
                      newFile();
                }
                //Si se elige guardar en el menu o en el toolbar
                if (e.getSource() == MGuardar || e.getSource() == BGuardar)
                       saveFile();
if (e.getSource() == BCopiar || e.getSource() == MCopiar)
                        editPane.copy();
                 if (e.getSource() == BCortar || e.getSource() == MCortar)
                        editPane.cut();
                 if (e.getSource() == BPegar|| e.getSource() == MPegar )
                        editPane.paste();
               if(e.getSource()==MImprimir || e.getSource()==BImprimir) {
               imprimir();
           }
               //Si se elige el boton abrir la lista del lado izquierdo
               if (e.getSource() == openSelectedButton)
                      openFile();
              };
      };
      ActionListener eventHandler = new EventHandler();
public Edit(String title)
{
      super(title);
}
//Agrega un archivo a la lista de la izquierda
public void agregaLista(String file)
{
      if (fileVector.contains(file))
              return;
      fileVector.add(file);
      Collections.sort(fileVector);
      list.setListData(fileVector);
}
//Dialogo que verifica si el usuario desea guardar el archivo
public void askSave()
{
      //Componente que muestra ventanas de opciones
      JOptionPane optionPane=new JOptionPane();
      Object[] opciones={"S Ì","No"};
      //Dialogo modal SI_NO
      int ret=optionPane.showOptionDialog(this,"Desea guardar?
","Pregunta",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null
,opciones,opciones[0]);
      //Si la opcion escogida es Si
      if(ret==JOptionPane.YES_OPTION)
              saveFile();
      }
//Suscribe los objetos al manejador de eventos eventHandler
public void initConnections()
{

    MNuevo.addActionListener(eventHandler);
    MAbrir.addActionListener(eventHandler);
    MGuardar.addActionListener(eventHandler);
    MSalir.addActionListener(eventHandler);
    MImprimir.addActionListener(eventHandler);
    MCopiar.addActionListener(eventHandler);
    MPegar.addActionListener(eventHandler);
MBuscar.addActionListener(eventHandler);
     tFuente.addActionListener(eventHandler);

     BAbrir.addActionListener(eventHandler);
     BGuardar.addActionListener(eventHandler);
     BCopiar.addActionListener(eventHandler);
     BCortar.addActionListener(eventHandler);
     BPegar.addActionListener(eventHandler);
     BImprimir.addActionListener(eventHandler);

     openSelectedButton.addActionListener(eventHandler);


}
//Inicializa las componentes de la aplicacion
public void initialize()
{
       //Define que el Layout del contenedor sea de tipo BorderLayout
       this.getContentPane().setLayout(new BorderLayout());

     // Clase anonima para que la aplicacion se cierre al apretar la X (boton esquina
superior derecha)
     this.addWindowListener(new WindowAdapter()
     {
           public void windowClosing(WindowEvent e)
           {
                 if (!isSaved && !editPane.getText().equals(""))
                askSave();
                 System.exit(0);
           }
     });

     /*****JMenuBar*****/
     menuBar = new JMenuBar();
     MArchivo = new JMenu("Archivo");
     MNuevo= new JMenuItem("Nuevo");
     MAbrir= new JMenuItem("Abrir");
     MGuardar= new JMenuItem("Guardar");
     MSalir= new JMenuItem("Salir");
     MImprimir= new JMenuItem("Imprimir");
     MEdicion= new JMenu("Edicion");
     MCopiar=new JMenuItem("Copiar");
     MPegar=new JMenuItem("Pegar");
     MBuscar=new JMenuItem("Buscar");
     areaFuente = new Font("Arial", Font.PLAIN, tama ño);
     Texto.setFont(areaFuente);

    scroll= new JScrollPane(Texto);
           getContentPane().add(scroll,BorderLayout.CENTER);
           JPanel panel= new JPanel();
           JPanel panel1= new JPanel();
           JPanel panel2= new JPanel();
           panel.setBackground(Color.lightGray);
panel1.setBackground(Color.lightGray);
      panel2.setBackground(Color.lightGray);
      getContentPane().add(panel,BorderLayout.SOUTH);
      getContentPane().add(panel1,BorderLayout.WEST);
      getContentPane().add(panel2,BorderLayout.EAST);
//Agrega los items al menu
MArchivo.add(MNuevo);
MArchivo.add(MAbrir);
MArchivo.add(MGuardar);
MArchivo.addSeparator();
MArchivo.add(MSalir);
MArchivo.add(MImprimir);
MEdicion.add(MCopiar);
MEdicion.add(MPegar);
MEdicion.add(MBuscar);
//Agrega el menu a la barra de menu
menuBar.add(MArchivo);
menuBar.add(MEdicion);
//Setea esa bara de menu para el frame
this.setJMenuBar(menuBar);


/*****JToolBar*****/
toolBar = new JToolBar();
BAbrir = new JButton();
BAbrir.setIcon(new ImageIcon(getClass().getResource("/open.gif")));
BAbrir.setMargin(new Insets(0, 0, 0, 0));
toolBar.add(BAbrir);

BGuardar = new JButton();
BGuardar.setIcon(new ImageIcon(getClass().getResource("/save.gif")));
BGuardar.setMargin(new Insets(0, 0, 0, 0));
toolBar.add(BGuardar);

toolBar.addSeparator();

BCopiar = new JButton();
BCopiar.setIcon(new ImageIcon(getClass().getResource("/copy.gif")));
BCopiar.setMargin(new Insets(0, 0, 0, 0));
toolBar.add(BCopiar);

BCortar = new JButton();
BCortar.setIcon(new ImageIcon(getClass().getResource("/cut.gif")));
BCortar.setMargin(new Insets(0, 0, 0, 0));
toolBar.add(BCortar);

BPegar = new JButton();
BPegar.setIcon(new ImageIcon(getClass().getResource("/paste.gif")));
BPegar.setMargin(new Insets(0, 0, 0, 0));
toolBar.add(BPegar);

toolBar.addSeparator();
BImprimir= new JButton();
    BImprimir.setIcon(new ImageIcon(getClass().getResource("/impresora.gif")));
    BImprimir.setMargin(new Insets(0, 0, 0, 0));
    toolBar.add(BImprimir);

    toolBar.addSeparator();

          tFuente= new JComboBox();
          tFuente.addItem("Tama ño Fuente");
          tFuente.addItem("10");
          tFuente.addItem("20");
          tFuente.addItem("30");
          tFuente.addItem("40");
          tFuente.addItem("50");
          tFuente.addItem("Personalizar");
          tFuente.setToolTipText("Tama ño de fuente");
          tFuente.addItemListener(
               new ItemListener () {
                    public void itemStateChanged(ItemEvent e) {

                         int elegido;
                         elegido=tFuente.getSelectedIndex();
                         switch (elegido) {

                              case 1:
                                   areaFuente= new Font("Arial", Font.PLAIN, 10);
                                   Texto.setFont(areaFuente);
                                   break;

                              case 2:
                                   areaFuente= new Font("Arial", Font.PLAIN, 20);
                                   Texto.setFont(areaFuente);
                                   break;

                              case 3:
                                   areaFuente= new Font("Arial", Font.PLAIN, 30);
                                   Texto.setFont(areaFuente);
                                   break;

                              case 4:
                                   areaFuente= new Font("Arial", Font.PLAIN, 40);
                                   Texto.setFont(areaFuente);
                                   break;

                              case 5:
                                   areaFuente= new Font("Arial", Font.PLAIN, 50);
                                   Texto.setFont(areaFuente);
                                   break;
                              case 6:

     tama ño=Integer.parseInt(JOptionPane.showInputDialog("Digite el tama ño de la
fuente"));
areaFuente= new Font("Arial", Font.PLAIN,
tama ño);
                                     Texto.setFont(areaFuente);
                                     break;
                           }
                     }
                }
           );
     toolBar.add(tFuente);
     //Agrega el toolbar en el norte del contenedor
     this.getContentPane().add(toolBar, BorderLayout.NORTH);

     /*****Status bar*****/
     statusPanel = new JPanel();
     statusPanel.setLayout(new BorderLayout());
     statusMsg1 = new JLabel("Estado: ");
     statusMsg2 = new JLabel();
     statusPanel.add(statusMsg1, BorderLayout.WEST);
     statusPanel.add(statusMsg2, BorderLayout.CENTER);
     //Agrega el panel de satus al sur del contenedor
     this.getContentPane().add(statusPanel, BorderLayout.SOUTH);

     /*****Text Editor*****/
     editPane = new JEditorPane();
     editPane.setText("");
     scrollPaneRight = new JScrollPane(editPane);

     /*****List*****/
     list=new JList();
     scrollPaneLeft=new JScrollPane(list);
     openSelectedButton=new JButton("Abrir");

     /*****leftPanel*****/
     leftPanel=new JPanel(new BorderLayout());
     leftPanel.add(scrollPaneLeft,BorderLayout.CENTER);
     leftPanel.add(openSelectedButton,BorderLayout.SOUTH);


     /*****Split Panel*****/
     //Define un contenedor con division izq-der
     splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
     splitPane.setRightComponent(scrollPaneRight);
     splitPane.setLeftComponent(leftPanel);
     this.getContentPane().add(splitPane, BorderLayout.CENTER);

}
public static void main(java.lang.String[] args)
{
      Edit aplication = new Edit("Editor De Texto Miguel A. Montano V.");
      aplication.initialize();
      aplication.initConnections();
      aplication.pack();
aplication.setSize(700, 500);
     aplication.setLocation(100, 100);
     aplication.setVisible(true);
}
//Para abrir un nuevo archivo en blanco
public void newFile()
{
      editPane.setText("");
      isSaved=false;

}
//Para abrir un achivo existente
public void openFile()
{
      //Si no existe el file chooser, crea uno
      if (fileChooser == null)
      {
              fileChooser = new JFileChooser();
      }
      //Valor que retorna al elegir una opcion en el file chooser
      int retVal = fileChooser.showOpenDialog(this);
      //Si se escogio Ok, (o abrir)
      if (retVal == fileChooser.APPROVE_OPTION)
      {
              //El path absoluto del archivo elegido
              fileName = fileChooser.getSelectedFile().getAbsolutePath();
              try
              {
                    //Pasa el nombre del archivo a URL
                    java.net.URL url = fileChooser.getSelectedFile().toURL();
                    statusMsg2.setText("abriendo " + fileName);
                    //Abre el archivo elegido en el panel de texto
                    editPane.setPage(url);
                    isSaved = false;
                    //Se agrega el archivo abierto a la lista de la izquierda
                    agregaLista("" + fileName);
              }
              catch (Exception ioe)
              {
                    statusMsg2.setText(ioe.getMessage());
              }
      }
}
//Abre el archivo seleccionado en la lista de la izquierda
public void openSelectedFile()
{
      if(list.getSelectedIndex()==-1)
              return;
      int ndx=list.getSelectedIndex();
      try
      {
              String name=(String)fileVector.get(ndx);
              java.net.URL url=(new java.io.File(name)).toURL();
editPane.setPage(url);
     }
     catch(Exception e)
     {
          statusMsg2.setText(e.getMessage());
     }
}
void imprimir ()
    {
       String todo=Texto.getText();
           PrintJob pjob = getToolkit().getPrintJob(this,"Imprimir Hoja",null);
                 Graphics pg= pjob.getGraphics();
                 pg.setFont(new Font("SansSerif",Font.PLAIN,10));
                 pg.drawString("Imprimido:",100,100);
                 int inicio=0;
                 int numlineas=1;
                 for (int i=0; i<todo.length();i++)
                  {
                    if((int) todo.charAt(i)==10)
                     {
                        pg.drawString(todo.substring(inicio,i-1),100,100 + (15 *
numlineas));
                        inicio=i+1;
                        numlineas ++;
                     }
                  }
                 pg.drawString (todo.substring(inicio,todo.length()),100,100 + (15 *
numlineas));
                 pg.dispose (); //Finalizar pagina
                 pjob.end(); //Termina trabajo y escupe pagina
    }

//Guarda el archivo que esta en el panel de texto
public void saveFile()
{
      //Utiliza un file chooser para explorar donde guardarlo
      //Si no existe, crea uno
      if (fileChooser == null)
      {
              fileChooser = new JFileChooser();
      }
      int retVal = fileChooser.showSaveDialog(this);
      if (retVal == fileChooser.APPROVE_OPTION)
      {
              fileName = fileChooser.getSelectedFile().getAbsolutePath();
              try
              {
                    statusMsg2.setText("Guardando "+fileName);
                    //Toma el texto que hay en el panel de texto
                    String text=editPane.getText();
                    java.io.FileWriter fileWriter=new java.io.FileWriter(fileName);
                    java.io.BufferedWriter br = new java.io.BufferedWriter(fileWriter);
                    br.write(text);
br.close();
             isSaved=true;
             //Agrega el archivo a la lista de la izquierda
             agregaLista(""+fileName);

        }
        catch (Exception ioe)
        {
             statusMsg2.setText(ioe.getMessage());
        }
    }

}

Más contenido relacionado

Destacado

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destacado (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Editortexto

  • 1. import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*; import java.io.*; public class Edit extends JFrame { //Inicializacion del tama ño de la fuente int tama ño=20; //Para explorar directorios para abrir y guardar archivos JFileChooser fileChooser = null; //Para escribir texto JEditorPane editPane; //Scroll del lado derecho JScrollPane scrollPaneRight; //Scroll del lado izquierdo JScrollPane scrollPaneLeft; //Panel izquierdo donde va la lista de archivo abiertos JPanel leftPanel; //La barra del Menu JMenuBar menuBar; //El menu JMenu MArchivo; JMenu MEdicion; //Los items del menu JMenuItem MNuevo; JMenuItem MAbrir; JMenuItem MGuardar; JMenuItem MSalir; JMenuItem MImprimir; JMenuItem MCortar; JMenuItem MPegar; JMenuItem MBuscar; JMenuItem MCopiar; JMenuItem Fuente; //Contenedor con division izquierda derecha JSplitPane splitPane; //El panel del estado y sus mensajes JPanel statusPanel; JLabel statusMsg1; JLabel statusMsg2; //Tool bar JToolBar toolBar; //Todos los botones JButton BCortar; JButton BAbrir; JButton BGuardar; JButton BCopiar; JButton BPegar; JButton BNuevo;
  • 2. JButton BImprimir; JButton openSelectedButton; private JComboBox tFuente; private Font areaFuente; private JScrollPane scroll; //cajas de texto JTextArea Texto = new JTextArea(); JTextArea Errores=new JTextArea(6,1); String Copiar=""; //La lista que se despliega en el lado izquierdo JList list; //Vector para almacenar los archivos abiertos Vector fileVector = new Vector(); String fileName; boolean isSaved = false; //Clase interna para manejar los eventos class EventHandler implements ActionListener { public void actionPerformed(ActionEvent e) { //Si se elige salir en el menu if (e.getSource() == MSalir) { //Si el archivo abierto no esta en blanco y no esta guardado if (!isSaved && !editPane.getText().equals("")) askSave(); System.exit(0); } //Si se elige abrir un archivo en el menu o con el boton de abrir en el toolbar if (e.getSource() == MAbrir || e.getSource() == BAbrir) { //misma verificacion anterior if (!isSaved && !editPane.getText().equals("")) askSave(); openFile(); } //Si se elige en el menu editar un archivo en blanco if (e.getSource() == MNuevo) { //idem if (!isSaved && !editPane.getText().equals("")) askSave(); newFile(); } //Si se elige guardar en el menu o en el toolbar if (e.getSource() == MGuardar || e.getSource() == BGuardar) saveFile();
  • 3. if (e.getSource() == BCopiar || e.getSource() == MCopiar) editPane.copy(); if (e.getSource() == BCortar || e.getSource() == MCortar) editPane.cut(); if (e.getSource() == BPegar|| e.getSource() == MPegar ) editPane.paste(); if(e.getSource()==MImprimir || e.getSource()==BImprimir) { imprimir(); } //Si se elige el boton abrir la lista del lado izquierdo if (e.getSource() == openSelectedButton) openFile(); }; }; ActionListener eventHandler = new EventHandler(); public Edit(String title) { super(title); } //Agrega un archivo a la lista de la izquierda public void agregaLista(String file) { if (fileVector.contains(file)) return; fileVector.add(file); Collections.sort(fileVector); list.setListData(fileVector); } //Dialogo que verifica si el usuario desea guardar el archivo public void askSave() { //Componente que muestra ventanas de opciones JOptionPane optionPane=new JOptionPane(); Object[] opciones={"S Ì","No"}; //Dialogo modal SI_NO int ret=optionPane.showOptionDialog(this,"Desea guardar? ","Pregunta",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null ,opciones,opciones[0]); //Si la opcion escogida es Si if(ret==JOptionPane.YES_OPTION) saveFile(); } //Suscribe los objetos al manejador de eventos eventHandler public void initConnections() { MNuevo.addActionListener(eventHandler); MAbrir.addActionListener(eventHandler); MGuardar.addActionListener(eventHandler); MSalir.addActionListener(eventHandler); MImprimir.addActionListener(eventHandler); MCopiar.addActionListener(eventHandler); MPegar.addActionListener(eventHandler);
  • 4. MBuscar.addActionListener(eventHandler); tFuente.addActionListener(eventHandler); BAbrir.addActionListener(eventHandler); BGuardar.addActionListener(eventHandler); BCopiar.addActionListener(eventHandler); BCortar.addActionListener(eventHandler); BPegar.addActionListener(eventHandler); BImprimir.addActionListener(eventHandler); openSelectedButton.addActionListener(eventHandler); } //Inicializa las componentes de la aplicacion public void initialize() { //Define que el Layout del contenedor sea de tipo BorderLayout this.getContentPane().setLayout(new BorderLayout()); // Clase anonima para que la aplicacion se cierre al apretar la X (boton esquina superior derecha) this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { if (!isSaved && !editPane.getText().equals("")) askSave(); System.exit(0); } }); /*****JMenuBar*****/ menuBar = new JMenuBar(); MArchivo = new JMenu("Archivo"); MNuevo= new JMenuItem("Nuevo"); MAbrir= new JMenuItem("Abrir"); MGuardar= new JMenuItem("Guardar"); MSalir= new JMenuItem("Salir"); MImprimir= new JMenuItem("Imprimir"); MEdicion= new JMenu("Edicion"); MCopiar=new JMenuItem("Copiar"); MPegar=new JMenuItem("Pegar"); MBuscar=new JMenuItem("Buscar"); areaFuente = new Font("Arial", Font.PLAIN, tama ño); Texto.setFont(areaFuente); scroll= new JScrollPane(Texto); getContentPane().add(scroll,BorderLayout.CENTER); JPanel panel= new JPanel(); JPanel panel1= new JPanel(); JPanel panel2= new JPanel(); panel.setBackground(Color.lightGray);
  • 5. panel1.setBackground(Color.lightGray); panel2.setBackground(Color.lightGray); getContentPane().add(panel,BorderLayout.SOUTH); getContentPane().add(panel1,BorderLayout.WEST); getContentPane().add(panel2,BorderLayout.EAST); //Agrega los items al menu MArchivo.add(MNuevo); MArchivo.add(MAbrir); MArchivo.add(MGuardar); MArchivo.addSeparator(); MArchivo.add(MSalir); MArchivo.add(MImprimir); MEdicion.add(MCopiar); MEdicion.add(MPegar); MEdicion.add(MBuscar); //Agrega el menu a la barra de menu menuBar.add(MArchivo); menuBar.add(MEdicion); //Setea esa bara de menu para el frame this.setJMenuBar(menuBar); /*****JToolBar*****/ toolBar = new JToolBar(); BAbrir = new JButton(); BAbrir.setIcon(new ImageIcon(getClass().getResource("/open.gif"))); BAbrir.setMargin(new Insets(0, 0, 0, 0)); toolBar.add(BAbrir); BGuardar = new JButton(); BGuardar.setIcon(new ImageIcon(getClass().getResource("/save.gif"))); BGuardar.setMargin(new Insets(0, 0, 0, 0)); toolBar.add(BGuardar); toolBar.addSeparator(); BCopiar = new JButton(); BCopiar.setIcon(new ImageIcon(getClass().getResource("/copy.gif"))); BCopiar.setMargin(new Insets(0, 0, 0, 0)); toolBar.add(BCopiar); BCortar = new JButton(); BCortar.setIcon(new ImageIcon(getClass().getResource("/cut.gif"))); BCortar.setMargin(new Insets(0, 0, 0, 0)); toolBar.add(BCortar); BPegar = new JButton(); BPegar.setIcon(new ImageIcon(getClass().getResource("/paste.gif"))); BPegar.setMargin(new Insets(0, 0, 0, 0)); toolBar.add(BPegar); toolBar.addSeparator();
  • 6. BImprimir= new JButton(); BImprimir.setIcon(new ImageIcon(getClass().getResource("/impresora.gif"))); BImprimir.setMargin(new Insets(0, 0, 0, 0)); toolBar.add(BImprimir); toolBar.addSeparator(); tFuente= new JComboBox(); tFuente.addItem("Tama ño Fuente"); tFuente.addItem("10"); tFuente.addItem("20"); tFuente.addItem("30"); tFuente.addItem("40"); tFuente.addItem("50"); tFuente.addItem("Personalizar"); tFuente.setToolTipText("Tama ño de fuente"); tFuente.addItemListener( new ItemListener () { public void itemStateChanged(ItemEvent e) { int elegido; elegido=tFuente.getSelectedIndex(); switch (elegido) { case 1: areaFuente= new Font("Arial", Font.PLAIN, 10); Texto.setFont(areaFuente); break; case 2: areaFuente= new Font("Arial", Font.PLAIN, 20); Texto.setFont(areaFuente); break; case 3: areaFuente= new Font("Arial", Font.PLAIN, 30); Texto.setFont(areaFuente); break; case 4: areaFuente= new Font("Arial", Font.PLAIN, 40); Texto.setFont(areaFuente); break; case 5: areaFuente= new Font("Arial", Font.PLAIN, 50); Texto.setFont(areaFuente); break; case 6: tama ño=Integer.parseInt(JOptionPane.showInputDialog("Digite el tama ño de la fuente"));
  • 7. areaFuente= new Font("Arial", Font.PLAIN, tama ño); Texto.setFont(areaFuente); break; } } } ); toolBar.add(tFuente); //Agrega el toolbar en el norte del contenedor this.getContentPane().add(toolBar, BorderLayout.NORTH); /*****Status bar*****/ statusPanel = new JPanel(); statusPanel.setLayout(new BorderLayout()); statusMsg1 = new JLabel("Estado: "); statusMsg2 = new JLabel(); statusPanel.add(statusMsg1, BorderLayout.WEST); statusPanel.add(statusMsg2, BorderLayout.CENTER); //Agrega el panel de satus al sur del contenedor this.getContentPane().add(statusPanel, BorderLayout.SOUTH); /*****Text Editor*****/ editPane = new JEditorPane(); editPane.setText(""); scrollPaneRight = new JScrollPane(editPane); /*****List*****/ list=new JList(); scrollPaneLeft=new JScrollPane(list); openSelectedButton=new JButton("Abrir"); /*****leftPanel*****/ leftPanel=new JPanel(new BorderLayout()); leftPanel.add(scrollPaneLeft,BorderLayout.CENTER); leftPanel.add(openSelectedButton,BorderLayout.SOUTH); /*****Split Panel*****/ //Define un contenedor con division izq-der splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); splitPane.setRightComponent(scrollPaneRight); splitPane.setLeftComponent(leftPanel); this.getContentPane().add(splitPane, BorderLayout.CENTER); } public static void main(java.lang.String[] args) { Edit aplication = new Edit("Editor De Texto Miguel A. Montano V."); aplication.initialize(); aplication.initConnections(); aplication.pack();
  • 8. aplication.setSize(700, 500); aplication.setLocation(100, 100); aplication.setVisible(true); } //Para abrir un nuevo archivo en blanco public void newFile() { editPane.setText(""); isSaved=false; } //Para abrir un achivo existente public void openFile() { //Si no existe el file chooser, crea uno if (fileChooser == null) { fileChooser = new JFileChooser(); } //Valor que retorna al elegir una opcion en el file chooser int retVal = fileChooser.showOpenDialog(this); //Si se escogio Ok, (o abrir) if (retVal == fileChooser.APPROVE_OPTION) { //El path absoluto del archivo elegido fileName = fileChooser.getSelectedFile().getAbsolutePath(); try { //Pasa el nombre del archivo a URL java.net.URL url = fileChooser.getSelectedFile().toURL(); statusMsg2.setText("abriendo " + fileName); //Abre el archivo elegido en el panel de texto editPane.setPage(url); isSaved = false; //Se agrega el archivo abierto a la lista de la izquierda agregaLista("" + fileName); } catch (Exception ioe) { statusMsg2.setText(ioe.getMessage()); } } } //Abre el archivo seleccionado en la lista de la izquierda public void openSelectedFile() { if(list.getSelectedIndex()==-1) return; int ndx=list.getSelectedIndex(); try { String name=(String)fileVector.get(ndx); java.net.URL url=(new java.io.File(name)).toURL();
  • 9. editPane.setPage(url); } catch(Exception e) { statusMsg2.setText(e.getMessage()); } } void imprimir () { String todo=Texto.getText(); PrintJob pjob = getToolkit().getPrintJob(this,"Imprimir Hoja",null); Graphics pg= pjob.getGraphics(); pg.setFont(new Font("SansSerif",Font.PLAIN,10)); pg.drawString("Imprimido:",100,100); int inicio=0; int numlineas=1; for (int i=0; i<todo.length();i++) { if((int) todo.charAt(i)==10) { pg.drawString(todo.substring(inicio,i-1),100,100 + (15 * numlineas)); inicio=i+1; numlineas ++; } } pg.drawString (todo.substring(inicio,todo.length()),100,100 + (15 * numlineas)); pg.dispose (); //Finalizar pagina pjob.end(); //Termina trabajo y escupe pagina } //Guarda el archivo que esta en el panel de texto public void saveFile() { //Utiliza un file chooser para explorar donde guardarlo //Si no existe, crea uno if (fileChooser == null) { fileChooser = new JFileChooser(); } int retVal = fileChooser.showSaveDialog(this); if (retVal == fileChooser.APPROVE_OPTION) { fileName = fileChooser.getSelectedFile().getAbsolutePath(); try { statusMsg2.setText("Guardando "+fileName); //Toma el texto que hay en el panel de texto String text=editPane.getText(); java.io.FileWriter fileWriter=new java.io.FileWriter(fileName); java.io.BufferedWriter br = new java.io.BufferedWriter(fileWriter); br.write(text);
  • 10. br.close(); isSaved=true; //Agrega el archivo a la lista de la izquierda agregaLista(""+fileName); } catch (Exception ioe) { statusMsg2.setText(ioe.getMessage()); } } }