elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Usando Git para manipular el directorio de trabajo, el índice y commits (segunda parte)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  Como cargar una documento .html
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Como cargar una documento .html  (Leído 5,259 veces)
EricCorona

Desconectado Desconectado

Mensajes: 19


Ver Perfil
Como cargar una documento .html
« en: 8 Diciembre 2009, 01:12 am »

Hola amigos  Estamos haciendo un miniNavegador y nos surgio la siguiente duda:

Como cargar un documento (un archivo con extensión .html) con contenido hipertextual y que en lugar de tags HTML tendrá tags especiales, las cuales se describen  abajo:

 Tag especial                     Significado
 <centrado></centrado>    Centra el texto que se encuentre dentro de la etiqueta.
 <negrita></negrita>    Da formato bold al texto que se encuentre dentro de la etiqueta.
 <cursiva></cursiva>    Da formato de cursiva al texto que se encuentre dentro de la etiqueta.
 <subrayado></subrayado>    Subraya el texto que se encuentre dentro de la etiqueta.
 <liga hacia=""></liga>    Permite poner un vínculo a un texto o imagen hacia una página.
 <imagen desde="" texto=""></imagen>    Permite poner una imagen en el documento con un texto alternativo.
 <vineta></vineta>    Coloca • viñetas al texto que se encuentre dentro de la etiqueta.
 <tachado></tachado>    Tacha el texto que se encuentre dentro de la etiqueta.
 <letra color="" tamano=""></letra>    Da color y tamaño al texto que se encuentre dentro de la etiqueta.
 <indice tipo=""></indice>    Coloca al texto que se encuentre dentro de la etiqueta como índice, ya sea superíndice o subíndice según el valor del atributo tipo, el cual puede ser sup (para superíndice) o sub (para subíndice).


les dejo el codigo:


/*
 * @name:       MiniNavegador.java ©Copyleft
 * @description:                  Este es un mini navegador en java
 * @author:       Eric Corona
 * @date:          5 de Diciembre de 2009
 * @version:       1.0
 */



import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import java.io.IOException;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.html.*; // <-- Esta es el package clave del mininavegador



// Clase que muestra un mini navegador ultra mega sencillo
public class MiniNavegador extends JFrame implements HyperlinkListener {


    // Botones de regreso y avance de las páginas:
    private JButton backButton, forwardButton;

    // Cajita de texto para la URL:
    private JTextField locationTextField;

    // Esta clase JEditorPane admite texto plano, HTML y RTF
    // Permite mezclar fuentes, colores e imágenes
    // Permite desplegar contenido HTML al indicarle el tipo de contenido (text/html):
    private JEditorPane displayEditorPane;

    // Este arreglo sirve para ir haciendo la lista de páginas visitadas:
    private ArrayList pageList = new ArrayList();

    // Método constructor del MiniNavegador:
    public MiniNavegador() {
        // Al extender de JFrame, le podemos poner un título de ventana al mini:
        super("Mini Navegador Ismael Perea");

        // Tamaño (ancho y largo) del mini:
        setSize(800, 700);

        // Manejo de la salida (exit) del mini:
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                actionExit();
            }
        });

        // Un pequeño menú (lo ideal es que le agreguen la opción de "Abrir archivo"):
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("Menú");
        fileMenu.setMnemonic(KeyEvent.VK_M);
        JMenuItem fileExitMenuItem = new JMenuItem("Salir", KeyEvent.VK_S);
        fileExitMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                actionExit();
            }
        });
        fileMenu.add(fileExitMenuItem);
        menuBar.add(fileMenu);
        setJMenuBar(menuBar);

        // Colocamos en el panel los botones del mini, además de la cajita del URL:
        JPanel buttonPanel = new JPanel();
        backButton = new JButton("< P'atrás");
        backButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                actionBack();
            }
        });
        backButton.setEnabled(false);
        buttonPanel.add(backButton);
        forwardButton = new JButton("P'adelante >");
        forwardButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                actionForward();
            }
        });
        forwardButton.setEnabled(false);
        buttonPanel.add(forwardButton);
        locationTextField = new JTextField("http://",35);
        locationTextField.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    actionGo();
                }
            }
        });
        buttonPanel.add(locationTextField);
        JButton goButton = new JButton("Cargar página >>");
        goButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                actionGo();
            }
        });
        buttonPanel.add(goButton);

        // Preparamos a JEditorPane para recibir HTML y desplegarlo bonito (con merengue):
        displayEditorPane = new JEditorPane();
        displayEditorPane.setContentType("text/html"); // <-- EL SECRETO DE TODO :)
        displayEditorPane.setEditable(false);
        displayEditorPane.addHyperlinkListener(this);

        // Página para precargar:
        String paginaInicial = "http://rigel.fca.unam.mx";
        String miBlog = "http://aprender.fca.unam.mx/~iperea";

        // Creo mi index:
        String  miIndex  = "<html><head><title>Ismael Perea Mini Navegador</title></head><center>";
              miIndex += "<body><b>Hola a todos mis alumnos</b><br />" + "<i>Este es mi mini navegador</i><br />";
              miIndex += "<font face=\"arial\">Como podr&aacute;n ver es muy sencillo</font><br />";
              miIndex += "<font face=\"courier\">pero funciona</font><br />";
              miIndex += "<font size=\"15\">para la clase de progra</font><br />";
              miIndex += "<font color=\"red\">y los caprichos del profe gru&ntilde;on... jejejejeje</font><br />";
              miIndex += "<img src=\"file:foto.png\" alt=\"Yo mero\"></img><br />";
              miIndex += "<a href=\"" + miBlog + "\">Mi blog</a></center>";
              miIndex += "</body></html>";

          displayEditorPane.setText(miIndex);

       

        /**************************************************************
        try{
           displayEditorPane.setPage(paginaInicial);
        }catch (IOException e) {
            System.err.println("No es posible cargar la página: " + e);
       }
      ***************************************************************/

        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(buttonPanel, BorderLayout.NORTH);
        getContentPane().add(new JScrollPane(displayEditorPane),
                BorderLayout.CENTER);
    }

    // Salir del mini:
    private void actionExit() {
        System.exit(0);
    }

    // Para regresar a la página anterior desde la actual:
    private void actionBack() {
        URL currentUrl = displayEditorPane.getPage();
        int pageIndex = pageList.indexOf(currentUrl.toString());
        try {
            showPage(
                    new URL((String) pageList.get(pageIndex - 1)), false);
        } catch (Exception e) {}
    }

    // Para ir a la página siguiente desde la actual:
    private void actionForward() {
        URL currentUrl = displayEditorPane.getPage();
        int pageIndex = pageList.indexOf(currentUrl.toString());
        try {
            showPage(
                    new URL((String) pageList.get(pageIndex + 1)), false);
        } catch (Exception e) {}
    }

    // Para cargar y mostrar la página ingresada en el campito de la URL:
    private void actionGo() {
        URL verifiedUrl = verifyUrl(locationTextField.getText());
        if (verifiedUrl != null) {
            showPage(verifiedUrl, true);
        } else {
            showError("¡No es una URL válida!");
        }
    }

    // Mostrar un mensaje de error:
    private void showError(String errorMessage) {
        JOptionPane.showMessageDialog(this, errorMessage,
                "¡¡¡¡ F I J A T E !!!!", JOptionPane.ERROR_MESSAGE);
    }

    // Verifica el formato de la URL:
    private URL verifyUrl(String url) {
        // Para que sólo permita URLs que utilicen el protocolo HTTP:
        if (!url.toLowerCase().startsWith("http://"))
            return null;

        // Verifica formato:
        URL verifiedUrl = null;
        try {
            verifiedUrl = new URL(url);
        } catch (Exception e) {
            return null;
        }

        return verifiedUrl;
    }


  // Despliega la página y la agrega a la lista de visitadas:

    private void showPage(URL pageUrl, boolean addToList) {
        // Muestra el bonito cursor de "espérame" mientras se carga la página:
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        try {
            // Obtener la URL de la página actual desplegada:
            URL currentUrl = displayEditorPane.getPage();

            // Carga la página en el JEditorPane:
            displayEditorPane.setPage(pageUrl);

            // Obtener la URL de la nueva página desplegada:
            URL newUrl = displayEditorPane.getPage();

            // Agregar la página a la lista:
            if (addToList) {
                int listSize = pageList.size();
                if (listSize > 0) {
                    int pageIndex =
                            pageList.indexOf(currentUrl.toString());
                    if (pageIndex < listSize - 1) {
                        for (int i = listSize - 1; i > pageIndex; i--) {
                            pageList.remove(i);
                        }
                    }
                }
                pageList.add(newUrl.toString());
            }

            // Actualizar el textito de la URL de la página cargada en ese momento:
            locationTextField.setText(newUrl.toString());

            // Actualiza los botones según la página cargada en ese momento:
            updateButtons();
        } catch (Exception e) {
            // Mensaje de error:
            showError("¡¡¡La página no se puede cargar!!!");
        } finally {
            // Regresar el cursor a su imagen original:
            setCursor(Cursor.getDefaultCursor());
        }
    }

     // Actualiza los botones del P'adelante o P'atrás:
    private void updateButtons() {
        if (pageList.size() < 2) {
            backButton.setEnabled(false);
            forwardButton.setEnabled(false);
        } else {
            URL currentUrl = displayEditorPane.getPage();
            int pageIndex = pageList.indexOf(currentUrl.toString());
            backButton.setEnabled(pageIndex > 0);
            forwardButton.setEnabled(
                    pageIndex < (pageList.size() - 1));
        }
    }

    // Manejo del click en las ligas de las páginas:
    public void hyperlinkUpdate(HyperlinkEvent event) {
        HyperlinkEvent.EventType eventType = event.getEventType();
        if (eventType == HyperlinkEvent.EventType.ACTIVATED) {
            if (event instanceof HTMLFrameHyperlinkEvent) {
                HTMLFrameHyperlinkEvent linkEvent =
                        (HTMLFrameHyperlinkEvent) event;
                HTMLDocument document =
                        (HTMLDocument) displayEditorPane.getDocument();
                document.processHTMLFrameHyperlinkEvent(linkEvent);
            } else {
                showPage(event.getURL(), true);
            }
        }
    }

    // Correr el mini:
    public static void main(String[] args) {
        MiniNavegador navegador = new MiniNavegador();
        navegador.show();
    }

} // Fin de la clase



En línea

Casidiablo
Desarrollador
Colaborador
***
Desconectado Desconectado

Mensajes: 2.919



Ver Perfil WWW
Re: Como cargar una documento .html
« Respuesta #1 en: 8 Diciembre 2009, 03:11 am »

Entiendo lo que quieres hacer, aunque no veo explícitamente que lo preguntes XD En fin... se me ocurren dos ideas, una más loca que la otra:

  • Extender la clase JEditorPane (o alguna de las superclases de esta) y sobrescribir los métodos (no se cuales son, tendrías que buscar) que hagan la parte del parsing de HTML.
  • Cuando recibas el archivo analizas las etiquetas que tiene y si ves algo como <centrado> lo cambias por <center> y luego sí se lo pasas al JEditorPane para que haga el renderizado HTML. (esta opción es la más sencilla, obviamente).

Un saludo!


En línea

EricCorona

Desconectado Desconectado

Mensajes: 19


Ver Perfil
Como mostrar una documento .html
« Respuesta #2 en: 10 Diciembre 2009, 19:34 pm »

/*
 * @name:          MiniNavegador.java ©Copyleft
 * @description:    Este es un mini navegador en java
 * @author:       Ismael Perea
 * @date:          16 de noviembre de 2009
 * @version:       1.0
 */



import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import java.io.IOException;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.html.*; // <-- Esta es el package clave del mininavegador
import java.io.File.*;
import javax.swing.JFileChooser.*;
/*
 * Revisen las siguientes ligas:
 * http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JEditorPane.html
 * http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JEditorPane.html
 * http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html
 */

// Clase que muestra un mini navegador ultra mega sencillo
public class MiniNavegador extends JFrame implements HyperlinkListener {


    // Botones de regreso y avance de las páginas:
    private JButton backButton, forwardButton;

    // Cajita de texto para la URL:
    private JTextField locationTextField;

    // Esta clase JEditorPane admite texto plano, HTML y RTF
    // Permite mezclar fuentes, colores e imágenes
    // Permite desplegar contenido HTML al indicarle el tipo de contenido (text/html):
    private JEditorPane displayEditorPane;

    // Este arreglo sirve para ir haciendo la lista de páginas visitadas:
    private ArrayList pageList = new ArrayList();

    // Método constructor del MiniNavegador:
    public MiniNavegador() {
        // Al extender de JFrame, le podemos poner un título de ventana al mini:
        super("Mini Navegador Del equipo $lang");

        // Tamaño (ancho y largo) del mini:
        setSize(800, 700);

        // Manejo de la salida (exit) del mini:
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                actionExit();
            }
        });

        // Un pequeño menú (lo ideal es que le agreguen la opción de "Abrir archivo"):
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("Menú");
        fileMenu.setMnemonic(KeyEvent.VK_M);
        JMenuItem fileExitMenuItem = new JMenuItem("Salir", KeyEvent.VK_S);
        fileExitMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                actionExit();
            }
        });
        fileMenu.add(fileExitMenuItem);
        menuBar.add(fileMenu);
        setJMenuBar(menuBar);



        // Crear boton abrir

        fileMenu.setMnemonic(KeyEvent.VK_A);
        JMenuItem fileOpenMenuItem = new JMenuItem("Abrir", KeyEvent.VK_A);
        fileOpenMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc = new JFileChooser("C:/");
        fc.showOpenDialog(fc);

        int returnVal =  fc.showOpenDialog(fc);
       
       Archivo selectedFile = null;

        if (returnVal== JFileChooser.APPROVE_OPTION)
            {
           selectedFile = fc.getSelectedFile();

            }

        //fileMenu.addActionListener();
            }
           
        });
        fileMenu.add(fileOpenMenuItem);
        menuBar.add(fileMenu);
        setJMenuBar(menuBar);

       
        // Colocamos en el panel los botones del mini, además de la cajita del URL:
        JPanel buttonPanel = new JPanel();
        backButton = new JButton("< P'atrás");
        backButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                actionBack();
            }
        });
        backButton.setEnabled(false);
        buttonPanel.add(backButton);
        forwardButton = new JButton("P'adelante >");
        forwardButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                actionForward();
            }
        });
        forwardButton.setEnabled(false);
        buttonPanel.add(forwardButton);
        locationTextField = new JTextField("http://",35);
        locationTextField.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    actionGo();
                }
            }
        });
        buttonPanel.add(locationTextField);
        JButton goButton = new JButton("Cargar página >>");
        goButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                actionGo();
            }
        });
        buttonPanel.add(goButton);

        // Preparamos a JEditorPane para recibir HTML y desplegarlo bonito (con merengue):
        displayEditorPane = new JEditorPane();
        displayEditorPane.setContentType("text/html"); // <-- EL SECRETO DE TODO)
        displayEditorPane.setEditable(false);
        displayEditorPane.addHyperlinkListener(this);

        // Página para precargar:
        String paginaInicial = "http://rigel.fca.unam.mx";
        String miBlog = "http://aprender.fca.unam.mx/~iperea";

        // Creo mi index:
        String  miIndex  = "<html><head><title>Ismael Perea Mini Navegador</title></head><center>";
              miIndex += "<body><b>Trabjo del Equipo $Lang</b><br />" + "<i>Este es un mini navegadorr</i><br />";
              miIndex += "<font color=\"red\">El browser deberia funcionar</font><br />";
              miIndex += "<img src=\"file:foto.png\"></img><br />";
              miIndex += "</body></html>";

          displayEditorPane.setText(miIndex);

        /*
         * ¿Qué pasa si comentas la línea de arriba y
         * descomentas el siguiente bloque?
         */

        /**************************************************************
        try{
           displayEditorPane.setPage(paginaInicial);
        }catch (IOException e) {
            System.err.println("No es posible cargar la página: " + e);
       }
      ***************************************************************/

        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(buttonPanel, BorderLayout.NORTH);
        getContentPane().add(new JScrollPane(displayEditorPane),
                BorderLayout.CENTER);
    }

    // Salir del mini:
    private void actionExit() {
        System.exit(0);
    }

    // Para regresar a la página anterior desde la actual:
    private void actionBack() {
        URL currentUrl = displayEditorPane.getPage();
        int pageIndex = pageList.indexOf(currentUrl.toString());
        try {
            showPage(
                    new URL((String) pageList.get(pageIndex - 1)), false);
        } catch (Exception e) {}
    }

    // Para ir a la página siguiente desde la actual:
    private void actionForward() {
        URL currentUrl = displayEditorPane.getPage();
        int pageIndex = pageList.indexOf(currentUrl.toString());
        try {
            showPage(
                    new URL((String) pageList.get(pageIndex + 1)), false);
        } catch (Exception e) {}
    }

    // Para cargar y mostrar la página ingresada en el campito de la URL:
    private void actionGo() {
        URL verifiedUrl = verifyUrl(locationTextField.getText());
        if (verifiedUrl != null) {
            showPage(verifiedUrl, true);
        } else {
            showError("¡No es una URL válida!");
        }
    }

    // Mostrar un mensaje de error:
    private void showError(String errorMessage) {
        JOptionPane.showMessageDialog(this, errorMessage,
                "¡¡¡¡ F I J A T E !!!!", JOptionPane.ERROR_MESSAGE);
    }

    // Verifica el formato de la URL:
    private URL verifyUrl(String url) {
        // Para que sólo permita URLs que utilicen el protocolo HTTP:
        if (!url.toLowerCase().startsWith("http://"))
            return null;

        // Verifica formato:
        URL verifiedUrl = null;
        try {
            verifiedUrl = new URL(url);
        } catch (Exception e) {
            return null;
        }

        return verifiedUrl;
    }


  // Despliega la página y la agrega a la lista de visitadas:

    private void showPage(URL pageUrl, boolean addToList) {
        // Muestra el bonito cursor de "espérame" mientras se carga la página:
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        try {
            // Obtener la URL de la página actual desplegada:
            URL currentUrl = displayEditorPane.getPage();

            // Carga la página en el JEditorPane:
            displayEditorPane.setPage(pageUrl);

            // Obtener la URL de la nueva página desplegada:
            URL newUrl = displayEditorPane.getPage();

            // Agregar la página a la lista:
            if (addToList) {
                int listSize = pageList.size();
                if (listSize > 0) {
                    int pageIndex =
                            pageList.indexOf(currentUrl.toString());
                    if (pageIndex < listSize - 1) {
                        for (int i = listSize - 1; i > pageIndex; i--) {
                            pageList.remove(i);
                        }
                    }
                }
                pageList.add(newUrl.toString());
            }

            // Actualizar el textito de la URL de la página cargada en ese momento:
            locationTextField.setText(newUrl.toString());

            // Actualiza los botones según la página cargada en ese momento:
            updateButtons();
        } catch (Exception e) {
            // Mensaje de error:
            showError("¡¡¡La página no se puede cargar!!!");
        } finally {
            // Regresar el cursor a su imagen original:
            setCursor(Cursor.getDefaultCursor());
        }
    }

     // Actualiza los botones del P'adelante o P'atrás:
    private void updateButtons() {
        if (pageList.size() < 2) {
            backButton.setEnabled(false);
            forwardButton.setEnabled(false);
        } else {
            URL currentUrl = displayEditorPane.getPage();
            int pageIndex = pageList.indexOf(currentUrl.toString());
            backButton.setEnabled(pageIndex > 0);
            forwardButton.setEnabled(
                    pageIndex < (pageList.size() - 1));
        }
    }

    // Manejo del click en las ligas de las páginas:
    public void hyperlinkUpdate(HyperlinkEvent event) {
        HyperlinkEvent.EventType eventType = event.getEventType();
        if (eventType == HyperlinkEvent.EventType.ACTIVATED) {
            if (event instanceof HTMLFrameHyperlinkEvent) {
                HTMLFrameHyperlinkEvent linkEvent =
                        (HTMLFrameHyperlinkEvent) event;
                HTMLDocument document =
                        (HTMLDocument) displayEditorPane.getDocument();
                document.processHTMLFrameHyperlinkEvent(linkEvent);
            } else {
                showPage(event.getURL(), true);
            }
        }
    }

    // Correr el mini:
    public static void main(String[] args) {
        MiniNavegador navegador = new MiniNavegador();
        navegador.show();
    }

} // Fin de la clase



Pueden ayudarme me marque error en lo siguiente

Archivo selectedFile = null;

        if (returnVal== JFileChooser.APPROVE_OPTION)
            {
           selectedFile = fc.getSelectedFile();

            }

        //fileMenu.addActionListener();
            }
En línea

Leyer


Desconectado Desconectado

Mensajes: 786


leyer@elhacker.net


Ver Perfil WWW
Re: Como cargar una documento .html
« Respuesta #3 en: 10 Diciembre 2009, 19:59 pm »

utiliza las etiquetas  code  :¬¬

SL2
En línea

Blitzkrieg'


Desconectado Desconectado

Mensajes: 546


print('Hi there')


Ver Perfil WWW
Re: Como cargar una documento .html
« Respuesta #4 en: 10 Diciembre 2009, 21:50 pm »

Código
  1. /*
  2.  * @name:          MiniNavegador.java ©Copyleft
  3.  * @description:    Este es un mini navegador en java
  4.  * @author:       Ismael Perea
  5.  * @date:          16 de noviembre de 2009
  6.  * @version:       1.0
  7.  */
  8.  
  9. import java.awt.*;
  10. import java.awt.event.*;
  11. import java.net.*;
  12. import java.util.*;
  13. import java.io.IOException;
  14. import javax.swing.*;
  15. import javax.swing.event.*;
  16. import javax.swing.text.html.*; // <-- Esta es el package clave del mininavegador
  17. import java.io.File.*;
  18. import javax.swing.JFileChooser.*;
  19. /*
  20.  * Revisen las siguientes ligas:
  21.  * http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JEditorPane.html
  22.  * http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JEditorPane.html
  23.  * http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html
  24.  */
  25.  
  26. // Clase que muestra un mini navegador ultra mega sencillo
  27. public class MiniNavegador extends JFrame implements HyperlinkListener {
  28.  
  29.  
  30.    // Botones de regreso y avance de las páginas:
  31.    private JButton backButton, forwardButton;
  32.  
  33.    // Cajita de texto para la URL:
  34.    private JTextField locationTextField;
  35.  
  36.    // Esta clase JEditorPane admite texto plano, HTML y RTF
  37.    // Permite mezclar fuentes, colores e imágenes
  38.    // Permite desplegar contenido HTML al indicarle el tipo de contenido (text/html):
  39.    private JEditorPane displayEditorPane;
  40.  
  41.    // Este arreglo sirve para ir haciendo la lista de páginas visitadas:
  42.    private ArrayList pageList = new ArrayList();
  43.  
  44.    // Método constructor del MiniNavegador:
  45.    public MiniNavegador() {
  46.        // Al extender de JFrame, le podemos poner un título de ventana al mini:
  47.        super("Mini Navegador Del equipo $lang");
  48.  
  49.        // Tamaño (ancho y largo) del mini:
  50.        setSize(800, 700);
  51.  
  52.        // Manejo de la salida (exit) del mini:
  53.        addWindowListener(new WindowAdapter() {
  54.            public void windowClosing(WindowEvent e) {
  55.                actionExit();
  56.            }
  57.        });
  58.  
  59.        // Un pequeño menú (lo ideal es que le agreguen la opción de "Abrir archivo"):
  60.        JMenuBar menuBar = new JMenuBar();
  61.        JMenu fileMenu = new JMenu("Menú");
  62.        fileMenu.setMnemonic(KeyEvent.VK_M);
  63.        JMenuItem fileExitMenuItem = new JMenuItem("Salir", KeyEvent.VK_S);
  64.        fileExitMenuItem.addActionListener(new ActionListener() {
  65.            public void actionPerformed(ActionEvent e) {
  66.                actionExit();
  67.            }
  68.        });
  69.        fileMenu.add(fileExitMenuItem);
  70.        menuBar.add(fileMenu);
  71.        setJMenuBar(menuBar);
  72.  
  73.  
  74.  
  75.        // Crear boton abrir
  76.  
  77.        fileMenu.setMnemonic(KeyEvent.VK_A);
  78.        JMenuItem fileOpenMenuItem = new JMenuItem("Abrir", KeyEvent.VK_A);
  79.        fileOpenMenuItem.addActionListener(new ActionListener() {
  80.            public void actionPerformed(ActionEvent e) {
  81.                JFileChooser fc = new JFileChooser("C:/");
  82.        fc.showOpenDialog(fc);
  83.  
  84.        int returnVal =  fc.showOpenDialog(fc);
  85.  
  86.       Archivo selectedFile = null;
  87.  
  88.        if (returnVal== JFileChooser.APPROVE_OPTION)
  89.            {
  90.           selectedFile = fc.getSelectedFile();
  91.  
  92.            }
  93.  
  94.        //fileMenu.addActionListener();
  95.            }
  96.  
  97.        });
  98.        fileMenu.add(fileOpenMenuItem);
  99.        menuBar.add(fileMenu);
  100.        setJMenuBar(menuBar);
  101.  
  102.  
  103.        // Colocamos en el panel los botones del mini, además de la cajita del URL:
  104.        JPanel buttonPanel = new JPanel();
  105.        backButton = new JButton("< P'atrás");
  106.        backButton.addActionListener(new ActionListener() {
  107.            public void actionPerformed(ActionEvent e) {
  108.                actionBack();
  109.            }
  110.        });
  111.        backButton.setEnabled(false);
  112.        buttonPanel.add(backButton);
  113.        forwardButton = new JButton("P'adelante >");
  114.        forwardButton.addActionListener(new ActionListener() {
  115.            public void actionPerformed(ActionEvent e) {
  116.                actionForward();
  117.            }
  118.        });
  119.        forwardButton.setEnabled(false);
  120.        buttonPanel.add(forwardButton);
  121.        locationTextField = new JTextField("http://",35);
  122.        locationTextField.addKeyListener(new KeyAdapter() {
  123.            public void keyReleased(KeyEvent e) {
  124.                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
  125.                    actionGo();
  126.                }
  127.            }
  128.        });
  129.        buttonPanel.add(locationTextField);
  130.        JButton goButton = new JButton("Cargar página >>");
  131.        goButton.addActionListener(new ActionListener() {
  132.            public void actionPerformed(ActionEvent e) {
  133.                actionGo();
  134.            }
  135.        });
  136.        buttonPanel.add(goButton);
  137.  
  138.        // Preparamos a JEditorPane para recibir HTML y desplegarlo bonito (con merengue):
  139.        displayEditorPane = new JEditorPane();
  140.        displayEditorPane.setContentType("text/html"); // <-- EL SECRETO DE TODO)
  141.        displayEditorPane.setEditable(false);
  142.        displayEditorPane.addHyperlinkListener(this);
  143.  
  144.        // Página para precargar:
  145.        String paginaInicial = "http://rigel.fca.unam.mx";
  146.        String miBlog = "http://aprender.fca.unam.mx/~iperea";
  147.  
  148.        // Creo mi index:
  149.        String  miIndex  = "<html><head><title>Ismael Perea Mini Navegador</title></head><center>";
  150.              miIndex += "<body><b>Trabjo del Equipo $Lang</b><br />" + "<i>Este es un mini navegadorr</i><br />";
  151.              miIndex += "<font color=\"red\">El browser deberia funcionar</font><br />";
  152.              miIndex += "<img src=\"file:foto.png\"></img><br />";
  153.              miIndex += "</body></html>";
  154.  
  155.          displayEditorPane.setText(miIndex);
  156.  
  157.        /*
  158.          * ¿Qué pasa si comentas la línea de arriba y
  159.          * descomentas el siguiente bloque?
  160.          */
  161.  
  162.        /**************************************************************
  163.         try{
  164.            displayEditorPane.setPage(paginaInicial);
  165.         }catch (IOException e) {
  166.             System.err.println("No es posible cargar la página: " + e);
  167.        }
  168.       ***************************************************************/
  169.  
  170.        getContentPane().setLayout(new BorderLayout());
  171.        getContentPane().add(buttonPanel, BorderLayout.NORTH);
  172.        getContentPane().add(new JScrollPane(displayEditorPane),
  173.                BorderLayout.CENTER);
  174.    }
  175.  
  176.    // Salir del mini:
  177.    private void actionExit() {
  178.        System.exit(0);
  179.    }
  180.  
  181.    // Para regresar a la página anterior desde la actual:
  182.    private void actionBack() {
  183.        URL currentUrl = displayEditorPane.getPage();
  184.        int pageIndex = pageList.indexOf(currentUrl.toString());
  185.        try {
  186.            showPage(
  187.                    new URL((String) pageList.get(pageIndex - 1)), false);
  188.        } catch (Exception e) {}
  189.    }
  190.  
  191.    // Para ir a la página siguiente desde la actual:
  192.    private void actionForward() {
  193.        URL currentUrl = displayEditorPane.getPage();
  194.        int pageIndex = pageList.indexOf(currentUrl.toString());
  195.        try {
  196.            showPage(
  197.                    new URL((String) pageList.get(pageIndex + 1)), false);
  198.        } catch (Exception e) {}
  199.    }
  200.  
  201.    // Para cargar y mostrar la página ingresada en el campito de la URL:
  202.    private void actionGo() {
  203.        URL verifiedUrl = verifyUrl(locationTextField.getText());
  204.        if (verifiedUrl != null) {
  205.            showPage(verifiedUrl, true);
  206.        } else {
  207.            showError("¡No es una URL válida!");
  208.        }
  209.    }
  210.  
  211.    // Mostrar un mensaje de error:
  212.    private void showError(String errorMessage) {
  213.        JOptionPane.showMessageDialog(this, errorMessage,
  214.                "¡¡¡¡ F I J A T E !!!!", JOptionPane.ERROR_MESSAGE);
  215.    }
  216.  
  217.    // Verifica el formato de la URL:
  218.    private URL verifyUrl(String url) {
  219.        // Para que sólo permita URLs que utilicen el protocolo HTTP:
  220.        if (!url.toLowerCase().startsWith("http://"))
  221.            return null;
  222.  
  223.        // Verifica formato:
  224.        URL verifiedUrl = null;
  225.        try {
  226.            verifiedUrl = new URL(url);
  227.        } catch (Exception e) {
  228.            return null;
  229.        }
  230.  
  231.        return verifiedUrl;
  232.    }
  233.  
  234.  
  235.  // Despliega la página y la agrega a la lista de visitadas:
  236.  
  237.    private void showPage(URL pageUrl, boolean addToList) {
  238.        // Muestra el bonito cursor de "espérame" mientras se carga la página:
  239.        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
  240.  
  241.        try {
  242.            // Obtener la URL de la página actual desplegada:
  243.            URL currentUrl = displayEditorPane.getPage();
  244.  
  245.            // Carga la página en el JEditorPane:
  246.            displayEditorPane.setPage(pageUrl);
  247.  
  248.            // Obtener la URL de la nueva página desplegada:
  249.            URL newUrl = displayEditorPane.getPage();
  250.  
  251.            // Agregar la página a la lista:
  252.            if (addToList) {
  253.                int listSize = pageList.size();
  254.                if (listSize > 0) {
  255.                    int pageIndex =
  256.                            pageList.indexOf(currentUrl.toString());
  257.                    if (pageIndex < listSize - 1) {
  258.                        for (int i = listSize - 1; i > pageIndex; i--) {
  259.                            pageList.remove(i);
  260.                        }
  261.                    }
  262.                }
  263.                pageList.add(newUrl.toString());
  264.            }
  265.  
  266.            // Actualizar el textito de la URL de la página cargada en ese momento:
  267.            locationTextField.setText(newUrl.toString());
  268.  
  269.            // Actualiza los botones según la página cargada en ese momento:
  270.            updateButtons();
  271.        } catch (Exception e) {
  272.            // Mensaje de error:
  273.            showError("¡¡¡La página no se puede cargar!!!");
  274.        } finally {
  275.            // Regresar el cursor a su imagen original:
  276.            setCursor(Cursor.getDefaultCursor());
  277.        }
  278.    }
  279.  
  280.     // Actualiza los botones del P'adelante o P'atrás:
  281.    private void updateButtons() {
  282.        if (pageList.size() < 2) {
  283.            backButton.setEnabled(false);
  284.            forwardButton.setEnabled(false);
  285.        } else {
  286.            URL currentUrl = displayEditorPane.getPage();
  287.            int pageIndex = pageList.indexOf(currentUrl.toString());
  288.            backButton.setEnabled(pageIndex > 0);
  289.            forwardButton.setEnabled(
  290.                    pageIndex < (pageList.size() - 1));
  291.        }
  292.    }
  293.  
  294.    // Manejo del click en las ligas de las páginas:
  295.    public void hyperlinkUpdate(HyperlinkEvent event) {
  296.        HyperlinkEvent.EventType eventType = event.getEventType();
  297.        if (eventType == HyperlinkEvent.EventType.ACTIVATED) {
  298.            if (event instanceof HTMLFrameHyperlinkEvent) {
  299.                HTMLFrameHyperlinkEvent linkEvent =
  300.                        (HTMLFrameHyperlinkEvent) event;
  301.                HTMLDocument document =
  302.                        (HTMLDocument) displayEditorPane.getDocument();
  303.                document.processHTMLFrameHyperlinkEvent(linkEvent);
  304.            } else {
  305.                showPage(event.getURL(), true);
  306.            }
  307.        }
  308.    }
  309.  
  310.    // Correr el mini:
  311.    public static void main(String[] args) {
  312.        MiniNavegador navegador = new MiniNavegador();
  313.        navegador.show();
  314.    }
  315.  
  316. } // Fin de la clase

Así queda mas legible el código, recuerda usar etiquetas code.

En cuanto al problema, pues como Casidiablo, sugiero que cuando el programa encuentre una etiqueta como <centrado> la convierta en <center>.
« Última modificación: 10 Diciembre 2009, 21:52 pm por Partenaire » En línea



Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines