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

 

 


Tema destacado: Guía actualizada para evitar que un ransomware ataque tu empresa


  Mostrar Mensajes
Páginas: 1 ... 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 [33] 34 35 36 37 38 39 40 41 42 43 44 45 46 47
321  Programación / Java / Re: URGENTE!!! ENVIAR ARCHIVOS POR MEDIO DE SOCKETS EN JAVA en: 16 Diciembre 2009, 00:47 am
Mirate esto, tal vez pueda ayudarte  ;D
322  Programación / Java / Re: Como cargar una documento .html 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>.
323  Foros Generales / Foro Libre / Re: ¿Quien es vuestro usuario favorito del Foro de elhacker.net? en: 10 Diciembre 2009, 15:17 pm
Kasswed sin duda  ;D
324  Foros Generales / Foro Libre / Re: ¿Quien es vuestro usuario favorito del Foro de elhacker.net? en: 10 Diciembre 2009, 12:39 pm
WHK, SDC, Novlucker y Casidiablo  ;D
325  Programación / Java / Re: MI EXAMEN en: 8 Diciembre 2009, 23:26 pm
Cambia de carrera  :¬¬ :¬¬
326  Programación / Java / Re: REPRODUCIR Y CONTROLAR AUDIO EN JAVA en: 8 Diciembre 2009, 16:50 pm
Hombre.... ayer mandé a que te borraran el mensaje por algo. Tienes que leer las reglas.... ¿qué te hace creer que escribiendo todo en mayúsculas y con una ortografía de un niño de 3 años se te va a ayudar?

Por encima se lo que quieres hacer... y sabes, tengo un exelente ejemplo de lo que quieres. Pero: 1ro ya lo he puesto en otros posts (tienes que usar el botón de BUSCAR) y 2do no me dan ganas de leer tu post.

Un saludo!


Te apoyo, Casidiablo posteo hace poco un ejemplo de como reproducir audio en Java, solo es cuestion de indagar en el foro de Java  :)
327  Foros Generales / Foro Libre / Re: Sus escritorios en: 5 Diciembre 2009, 19:00 pm
Todo ordenadito, asi me gusta!
328  Programación / Java / Re: Pasar archivo de texto (.txt) a mayuscula en: 5 Diciembre 2009, 01:46 am
Nada mejor que lo que te puso Darius
329  Media / Diseño Gráfico / Re: [Juego de diseño] El Staff de elhacker.net en: 4 Diciembre 2009, 23:48 pm
Muy bueno el de los osos.
330  Seguridad Informática / Nivel Web / Re: Libro en: 4 Diciembre 2009, 22:02 pm
Voy a empezar aprendiendo bien javascript, algun manual o libro bien completico que me recomienden?
Páginas: 1 ... 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 [33] 34 35 36 37 38 39 40 41 42 43 44 45 46 47
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines