begin process at 2010 09 06 05:28:16
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Swing

 > HTML BROWSER AVEC LES FONCTINO DE BASES DE JAVA

HTML BROWSER AVEC LES FONCTINO DE BASES DE JAVA


 Information sur la source

Note :
10 / 10 - par 2 personnes
10,00 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10
Catégorie :Swing Niveau :Initié Date de création :18/11/2003 Vu / téléchargé :10 571 / 885

Auteur : GodConan

Ecrire un message privé
Commentaire sur cette source (12)
Ajouter un commentaire et/ou une note

 Description

Cliquez pour voir la capture en taille normale
C est un ptt browser html qui permet de voir la plus part des pages. Exemple de simpliciter ;o) et d utilisation de JEditorPane evec les class java par defaut
Personnelement j utilise une class derivée de celle ci pour afficher mes aides dans mes applications... ;o); Elle est tre facil a adapter et surtou reagie bcp plus vite qu un appele au browser par defaut de Windo..
j ai aussi fait le Main d exemple d utilisation avec une page Htlm en argument...


bonne prog...

Source

  • import java.awt.*;
  • import java.io.IOException;
  • import java.net.MalformedURLException;
  • import java.net.URL;
  • import java.util.StringTokenizer;
  • import java.util.Vector;
  • import javax.swing.*;
  • import javax.swing.event.HyperlinkEvent;
  • import javax.swing.event.HyperlinkListener;
  • import javax.swing.text.html.HTMLDocument;
  • import javax.swing.text.html.HTMLFrameHyperlinkEvent;
  • /**
  • * @author GodConan
  • *
  • */
  • public class HtmlBrowser extends JFrame
  • {
  • JEditorPane html;
  • String path = "index.html";
  • Vector oldPages = new Vector(); // sauve les path des page deja passer
  • int currentPageIdx = 0;
  • public HtmlBrowser() throws HeadlessException
  • {
  • super();
  • setSize( 500, 500 );
  • JPanel2.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));
  • JPanel2.add(JToolBar1);
  • JToolBar1.add(btnPrev);
  • JToolBar1.add(btnNext);
  • btnPrev.setText("Page precédente");
  • btnNext.setText("Page suivante");
  • Actions aIcareAction = new Actions();
  • btnPrev.addActionListener( aIcareAction );
  • btnNext.addActionListener( aIcareAction );
  • btnNext.setFocusPainted( false );
  • btnPrev.setFocusPainted( false );
  • btnNext.setEnabled( false );
  • btnPrev.setEnabled( false );
  • try
  • {
  • URL url = getURL( path );
  • html = new JEditorPane( url );
  • html.setEditable(false);
  • html.addHyperlinkListener( createHyperLinkListener() );
  • html.setBounds( 0, 0, 500, 500 );
  • JScrollPane scroller = new JScrollPane();
  • JViewport vp = scroller.getViewport();
  • vp.add( html );
  • getContentPane().add( JPanel2, BorderLayout.NORTH );
  • getContentPane().add( scroller, BorderLayout.CENTER);
  • html.setBackground( this.getBackground() );
  • }
  • catch (Exception e)
  • {
  • System.out.println("eror : " + e );
  • }
  • }
  • JPanel JPanel2 = new JPanel();
  • JToolBar JToolBar1 = new JToolBar();
  • JButton btnPrev = new JButton();
  • JButton btnNext = new JButton();
  • class Actions implements java.awt.event.ActionListener
  • {
  • public void actionPerformed(java.awt.event.ActionEvent event)
  • {
  • Object object = event.getSource();
  • if (object == btnNext )
  • btnNext_actionPerformed(event);
  • else if (object == btnPrev)
  • btnPrev_actionPerformed(event);
  • }
  • }
  • private void btnNext_actionPerformed(java.awt.event.ActionEvent event)
  • {
  • try {
  • if( currentPageIdx++ < oldPages.size() )
  • {
  • String p = (String)oldPages.elementAt( currentPageIdx );
  • URL url = getURL( p );
  • html.setPage( url );
  • }
  • checkBtn();
  • } catch (Exception e)
  • {
  • System.out.println( " btnNext_actionPerformed : " + e );
  • }
  • }
  • private void btnPrev_actionPerformed(java.awt.event.ActionEvent event)
  • {
  • try {
  • if( currentPageIdx > 0 && !oldPages.isEmpty() )
  • {
  • String p = (String)oldPages.elementAt( --currentPageIdx );
  • URL url = getURL( p );
  • html.setPage( url );
  • }
  • checkBtn();
  • } catch (Exception e)
  • {
  • System.out.println( " btnNext_actionPerformed : " + e );
  • }
  • }
  • private void initTitre( String p )
  • {
  • String sep = "?";
  • if ( p.indexOf( "/" ) > 0 ) sep = "/";
  • else if ( p.indexOf( "\\" ) > 0 ) sep = "\\";
  • StringTokenizer st = new StringTokenizer( p, sep );
  • int n = st.countTokens();
  • String s = "";
  • while( st.hasMoreTokens() ) { s = st.nextToken(); }
  • if ( s.indexOf(".") > 0 ) s = s.substring( 0, s.indexOf( "." ) );
  • this.setTitle( "Page : " + s );
  • }
  • public HtmlBrowser( String titre ) throws HeadlessException
  • {
  • this();
  • this.setTitle( titre );
  • }
  • private void checkBtn()
  • {
  • if ( oldPages == null || oldPages.size() == 0 )
  • {
  • btnNext.setEnabled( false );
  • btnPrev.setEnabled( false );
  • }
  • else
  • {
  • if ( currentPageIdx > 0 )
  • btnPrev.setEnabled( true );
  • else
  • btnPrev.setEnabled( false );
  • if ( (currentPageIdx+1) < oldPages.size() )
  • btnNext.setEnabled( true );
  • else
  • btnNext.setEnabled( false );
  • }
  • }
  • private HyperlinkListener createHyperLinkListener()
  • {
  • return new HyperlinkListener()
  • {
  • public void hyperlinkUpdate(HyperlinkEvent e)
  • {
  • if ( e.getEventType() == HyperlinkEvent.EventType.ACTIVATED )
  • {
  • if (e instanceof HTMLFrameHyperlinkEvent)
  • {
  • ((HTMLDocument) html
  • .getDocument())
  • .processHTMLFrameHyperlinkEvent(
  • (HTMLFrameHyperlinkEvent) e);
  • }
  • else
  • {
  • try
  • {
  • path = e.getURL().getPath();
  • html.setPage( e.getURL() );
  • addHisto( path );
  • initTitre( path );
  • }
  • catch (IOException ioe)
  • {
  • System.out.println("IOE: " + ioe);
  • }
  • }
  • }
  • }
  • };
  • }
  • private void addHisto( String path )
  • {
  • oldPages.add( path );
  • currentPageIdx = oldPages.size() - 1;
  • if ( oldPages.size() > 25 )
  • {
  • oldPages = new Vector();
  • oldPages.add( path );
  • currentPageIdx = oldPages.size() - 1;
  • }
  • checkBtn();
  • }
  • /**
  • * Returns le path de la page en cour de lecture.
  • * @return String
  • */
  • public String getPath()
  • {
  • return path;
  • }
  • /**
  • * Sets le path de la page html a lire.
  • * @param path de la page html
  • */
  • public void setPath(String path)
  • {
  • try
  • {
  • this.path = path;
  • URL url = getURL( path );
  • html.setPage( url );
  • addHisto( path );
  • }
  • catch (Exception e)
  • {
  • System.out.println("setPath : " + e );
  • }
  • }
  • public void setDocument( String doc )
  • {
  • html.setText( doc );
  • }
  • public URL getURL( String file ) throws MalformedURLException
  • {
  • URL documentBase = new URL("file:///" + System.getProperty("user.dir") + "/");
  • return new URL( documentBase, file );
  • }
  • public static void main(String[] args)
  • {
  • HtmlBrowser b = new HtmlBrowser();
  • if ( args.length > 0 ) b.setPath( args[ 0 ] );
  • b.setLocation( new Point( 0, 0 ) );
  • b.setVisible( true );
  • }
  • }
import java.awt.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLFrameHyperlinkEvent;
/**
 * @author GodConan
 *
 */
public class HtmlBrowser extends JFrame 
{
    JEditorPane html;
    String path = "index.html";
    Vector oldPages = new Vector(); // sauve les path des page deja passer
    int currentPageIdx = 0;
    
    public HtmlBrowser() throws HeadlessException
    {
        super();
        setSize( 500, 500 );
        JPanel2.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));
        JPanel2.add(JToolBar1);
        JToolBar1.add(btnPrev);
        JToolBar1.add(btnNext);
        btnPrev.setText("Page precédente");
        btnNext.setText("Page suivante");

        Actions aIcareAction = new Actions();
        btnPrev.addActionListener( aIcareAction );
        btnNext.addActionListener( aIcareAction );
        btnNext.setFocusPainted( false );
        btnPrev.setFocusPainted( false );
        btnNext.setEnabled( false );
        btnPrev.setEnabled( false );

        try
        {
            URL url = getURL( path );
            html = new JEditorPane( url );
            html.setEditable(false);
            html.addHyperlinkListener( createHyperLinkListener() );
            html.setBounds( 0, 0, 500, 500 );
            JScrollPane scroller = new JScrollPane();
            JViewport vp = scroller.getViewport();
            vp.add( html );
            getContentPane().add( JPanel2, BorderLayout.NORTH );
            getContentPane().add( scroller, BorderLayout.CENTER);
            html.setBackground( this.getBackground() );
        }
        catch (Exception e)
        {
            System.out.println("eror : " + e );
        }
    }
    JPanel JPanel2 = new JPanel();
    JToolBar JToolBar1 = new JToolBar();
    JButton btnPrev = new JButton();
    JButton btnNext = new JButton();

    class Actions implements java.awt.event.ActionListener
    {
        public void actionPerformed(java.awt.event.ActionEvent event)
        {
            Object object = event.getSource();
            if (object == btnNext )
                btnNext_actionPerformed(event);
            else if (object == btnPrev)
                btnPrev_actionPerformed(event);
        }
    }
    
    private void btnNext_actionPerformed(java.awt.event.ActionEvent event)
    {
        try {
            if( currentPageIdx++ < oldPages.size() ) 
            {
                String p = (String)oldPages.elementAt( currentPageIdx );
                URL url = getURL( p );
                html.setPage( url );
            }
            checkBtn();            
        } catch (Exception e) 
        {
            System.out.println( " btnNext_actionPerformed : " + e );
        }
    }

    private void btnPrev_actionPerformed(java.awt.event.ActionEvent event)
    {
        try {
            if( currentPageIdx > 0 && !oldPages.isEmpty() ) 
            {
                String p = (String)oldPages.elementAt( --currentPageIdx );
                URL url = getURL( p );
                html.setPage( url );
            }
            checkBtn();            
        } catch (Exception e) 
        {
            System.out.println( " btnNext_actionPerformed : " + e );
        }
    }

    private void initTitre( String p )
    {
        String sep = "?";
        if ( p.indexOf( "/" ) > 0 ) sep = "/";
        else if ( p.indexOf( "\\" ) > 0 ) sep = "\\";
        StringTokenizer st = new StringTokenizer( p, sep );
        int n = st.countTokens();
        String s = "";
        while( st.hasMoreTokens() ) { s = st.nextToken(); }
        if ( s.indexOf(".") > 0 ) s = s.substring( 0, s.indexOf( "." ) );
        this.setTitle( "Page : " + s );
    }
    
    public HtmlBrowser( String titre ) throws HeadlessException
    {
        this();
        this.setTitle( titre );
    }

    private void checkBtn()
    {
        if ( oldPages == null || oldPages.size() == 0 )
        {
            btnNext.setEnabled( false );
            btnPrev.setEnabled( false );
        }
        else 
        {
            if ( currentPageIdx > 0 )
                btnPrev.setEnabled( true );
            else 
                btnPrev.setEnabled( false );
            if ( (currentPageIdx+1) < oldPages.size() )
                btnNext.setEnabled( true );
            else 
                btnNext.setEnabled( false );
        }
    }
    
    private HyperlinkListener createHyperLinkListener()
    {
        return new HyperlinkListener()
                            {
                                public void hyperlinkUpdate(HyperlinkEvent e)
                                {
                                    if ( e.getEventType() == HyperlinkEvent.EventType.ACTIVATED )
                                    {
                                        if (e instanceof HTMLFrameHyperlinkEvent)
                                        {
                                            ((HTMLDocument) html
                                                    .getDocument())
                                                    .processHTMLFrameHyperlinkEvent(
                                                (HTMLFrameHyperlinkEvent) e);
                                        }
                                        else
                                        {
                                            try
                                            {
                                                path = e.getURL().getPath();
                                                html.setPage( e.getURL() );
                                                addHisto( path );
                                                initTitre( path );
                                            }
                                            catch (IOException ioe)
                                            {
                                                System.out.println("IOE: " + ioe);
                                            }
                                        }
                                    }
                                }
                            };
    }
    
    private void addHisto( String path )
    {
        oldPages.add( path );
        currentPageIdx = oldPages.size() - 1;
        if ( oldPages.size() > 25 ) 
        {
            oldPages = new Vector();
            oldPages.add( path );
            currentPageIdx = oldPages.size() - 1;
        }
        checkBtn();
    }
    
    /**
     * Returns le path de la page en cour de lecture.
     * @return String
     */
    public String getPath()
    {
        return path;
    }

    /**
     * Sets le path de la page html a lire.
     * @param path de la page html
     */
    public void setPath(String path)
    {
        try 
        {
            this.path = path;
            URL url = getURL( path );
            html.setPage( url );
            addHisto( path );
        } 
        catch (Exception e) 
        {
            System.out.println("setPath  : " + e );
        }

    }
    
    public void setDocument( String doc )
    {
        html.setText( doc );
    }

    public URL getURL( String file ) throws MalformedURLException
    {
        URL documentBase = new URL("file:///" + System.getProperty("user.dir") + "/");
        return new URL( documentBase, file );
    }

    public static void main(String[] args)
    {
        HtmlBrowser b = new HtmlBrowser();
        if ( args.length > 0 ) b.setPath( args[ 0 ] );
        b.setLocation( new Point( 0, 0 ) );
        b.setVisible( true );
    }

}

 Conclusion

bon c vrai que chui pas un fou des commentaires mais je suis tout 'ouï' ;o) ...
et puis ce pett code reste trés lisible... ;o)



 Fichier Zip

Les Membres Club peuvent télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip


 Sources du même auteur

Source avec Zip Source avec une capture GESTION DE STOCK AVEC DATE LIMITE (MYSQL, JTREE, TREEMODEL E...
Source avec Zip TRANFER MULTIPLE DE MAIL A PARTIR D UN FICHIER D ADDRESSE
Source avec Zip Source avec une capture JEU DE PONG DONNANT DE BONNES BASE POUR LA PROGRAMMATION GRA...
Source avec Zip CLASS D'ARCHIVAGE/DESARCHIVAGE ;O) DS UN FICHIER DE TYPE ZIP
Source avec Zip Source avec une capture TRACER DE COURBE A PARTIR D UNE JTABLE

 Sources de la même categorie

AUTOCOMPLETION TEXT par miupri4
Source avec Zip Source avec une capture DECALQUER UN DESSIN par Julien39
Source avec Zip Source avec une capture JBUTTON PERSONNALISÉS par Julien39
Source avec Zip Source avec une capture BULLES D'AQUARIUM QUI SE DÉPLACENT (AVEC POISSON) par Julien39
Source avec Zip Source avec une capture LOGICIEL COMPTABLE (ACCOUNTANT) (COMPTE, BALANCE) par Kidator

Commentaires et avis

Commentaire de UNi le 20/11/2003 12:28:15

salut !!

ton prog est plutot simple mais ca donne des idées pour voir comment développer une vrai Browser !!

PS : ta oublier le fonction pour fermer le prog car la il reste en memoire !!

ExitWindow exit = new ExitWindow();
b.addWindowListener(exit);

Commentaire de GodConan le 20/11/2003 18:42:42

yup je sais ;o) chui plutot feneant ;o) je la mets jamais sur mes sample ;o)

et en effet  ;o) je le di c un sample  ;o) donc il demande K etre amelioree ;o)

Commentaire de copsblondin le 11/03/2004 17:37:06

Salut,

J'ai un petit soucis avec ton programme, impossible de l'exécuter. il me mais une erreur:"Exception in thread "main" java.NoClassDefoundError: HtmlBrowser". Vu que je débute je ne pige pas tout.

Commentaire de GodConan le 11/03/2004 18:50:11

ben la c kil ne trouve pas la class  ;o)
t sur que tu la compiler avant? ;o)

Commentaire de copsblondin le 11/03/2004 19:30:33

Oui j'l'ai bien compiler, et tjs le meme soucis!!

Commentaire de copsblondin le 11/03/2004 19:31:09

Oui j'l'ai bien compiler, et tjs le meme soucis!! Ke fait ton prog au juste?

Commentaire de copsblondin le 11/03/2004 19:31:44

Oui j'l'ai bien compiler, et tjs le meme soucis!! Ke fait ton prog au juste?

Commentaire de GodConan le 11/03/2004 21:16:52

ben c sur l image ;o)
il affiche une page HTML ;o)

Commentaire de candide2 le 17/03/2004 11:51:02

Bonjour,
ton code est intéressant, mais j'ai cette exception quand je passe la souris sur la frontière basse de la JScrollPane (juste au dessus de la limite de la fenêtre.
Des idées ?

java.lang.NullPointerException
        at javax.swing.text.html.HTMLEditorKit$LinkController.doesElementContainLocation(HTMLEditorKit.java:733)
        at javax.swing.text.html.HTMLEditorKit$LinkController.mouseMoved(HTMLEditorKit.java:631)
        at java.awt.AWTEventMulticaster.mouseMoved(AWTEventMulticaster.java:268)
        at java.awt.Component.processMouseMotionEvent(Component.java:5066)
        at javax.swing.JComponent.processMouseMotionEvent(JComponent.java:2763)
        at java.awt.Component.processEvent(Component.java:4822)
        at java.awt.Container.processEvent(Container.java:1525)
        at java.awt.Component.dispatchEventImpl(Component.java:3526)
        at java.awt.Container.dispatchEventImpl(Container.java:1582)
        at java.awt.Component.dispatchEvent(Component.java:3367)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3359)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3087)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3004)
        at java.awt.Container.dispatchEventImpl(Container.java:1568)
        at java.awt.Window.dispatchEventImpl(Window.java:1581)
        at java.awt.Component.dispatchEvent(Component.java:3367)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:445)
        at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:191)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:144)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)

Commentaire de GodConan le 17/03/2004 18:45:10

la trace remonte pas asser loin ;o) pour voir ;o)
mais bon je suis presque sur que c a cause d un truc HTML ds ta page pas compris par le JEditor faut reconnaitre que c un browser de base ;o) il utilise les class fournis par Sun et le parser HTML n est pas vraiment complet ... ;o) voila ;o)


gl
++

Commentaire de candide2 le 18/03/2004 09:13:30

Tu as raison, apparemment il ne support pas bien les frames.
Si j'ai une page avec des frames en "cols", c'est à la frontière du bas que j'ai une exception et si c'est des frames en "rows", c'est la frontière droite.
@+

Commentaire de banouigu le 30/10/2007 12:05:41

bjr,
je suis en train de realiser un browser et c'est la premiere fois que je vais faire ce type de programme,je travaille sur eclipse,j'ai essayer ton programme mais sa marche pa.est ce que tu pe me l'expliquer. merci d'avance

 Ajouter un commentaire




Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Septembre 2010
LMMJVSD
  12345
6789101112
13141516171819
20212223242526
27282930   

Consulter la suite du CalendriCode

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 1,498 sec (4)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales