Navigazione

    Privacy - Termini e condizioni
    © 2020 Search On Media Group S.r.l.
    • Registrati
    • Accedi
    • CATEGORIES
    • Discussioni
    • Non letti
    • Recenti
    • Hashtags
    • Popolare
    • Utenti
    • Stream
    • Interest
    • Categories
    1. Home
    2. chicco80
    3. Post
    C

    chicco80

    @chicco80

    • Profilo
    • Chi segue 0
    • Da chi è seguito 0
    • Discussioni 2
    • Post 2
    • Migliore 0
    • Gruppi 0
    Iscrizione Ultimo Accesso
    0
    Reputazione
    2
    Post
    0
    Visite al profilo
    0
    Da chi è seguito
    0
    Chi segue
    User Newbie

    Post creati da chicco80

    • Implementazione parser java

      Salve a tutti,
      ho un (piccolo) problema: ho realizzato un browser in java e dovrei eseguire il parsing di file xml. Per il parsing utilizzo la classe SAXTreeViewer, ma non riesco a implementarla nel codice browser. Sapreste darmi una mano?
      grazie

      browser:

      class Webbrowser implements ActionListener
      {
      JTextField t1;
      JLabel l1;
      JButton b1;
      GridBagLayout gbl;
      GridBagConstraints gbc;
      JPanel p;
      JFrame frame;
      JScrollPane scrollPane;
      JEditorPane jep;
      static String initialPage;

      public Webbrowser()
      {
      //JFrame.setDefaultLookAndFeelDecorated(true);
      /try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAn dFeelClassName());
      }
      catch(Exception e)
      {
      e.printStackTrace();
      }
      /
      frame=new JFrame("Chicco's Web Browser");

      gbl=new GridBagLayout();
      gbc=new GridBagConstraints();

      p=new JPanel();
      p.setLayout(gbl);

      jep = new JEditorPane();

      t1=new JTextField();

      b1=new JButton("Trova");
      b1.addActionListener(this);
      frame.getRootPane().setDefaultButton(b1);

      l1=new JLabel("Indirizzo");

      gbc.anchor=GridBagConstraints.NORTHEAST;
      gbc.fill=GridBagConstraints.HORIZONTAL;
      gbc.gridx=0;
      gbc.gridy=0;
      gbc.weightx=0.0;
      gbl.setConstraints(l1,gbc);
      p.add(l1);

      gbc.anchor=GridBagConstraints.NORTHEAST;
      gbc.gridx=1;
      gbc.gridy=0;
      gbc.weightx=1.0;
      gbl.setConstraints(t1,gbc);
      p.add(t1);

      gbc.anchor=GridBagConstraints.NORTHWEST;
      gbc.gridx=2;
      gbc.gridy=0;
      gbc.weightx=0.0;
      gbl.setConstraints(b1,gbc);
      p.add(b1);

      scrollPane = new JScrollPane(jep);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);

      frame.getContentPane().add(p,BorderLayout.NORTH);
      frame.getContentPane().add(scrollPane);
      frame.setSize(1000,700);
      frame.setVisible(true);
      }

      public void actionPerformed(ActionEvent e)
      {
      initialPage=t1.getText();
      char a=initialPage.charAt(0);
      char b=initialPage.charAt(1);
      char c=initialPage.charAt(2);
      char d=initialPage.charAt(3);
      char ea=initialPage.charAt(4);
      char f=initialPage.charAt(5);
      char g=initialPage.charAt(6);

      if((a=='h')&&(b=='t')&&(c=='t')&&(d=='p')&&(ea==': ')&&(f=='/')&&(g=='/'))
      {
      initialPage=t1.getText();
      }
      else
      {
      initialPage="<A href="http://"+initialPage">http://"+initialPage;
      }
      jep.setEditable(false);
      jep.addHyperlinkListener(new second(jep));
      try
      {
      jep.setPage(initialPage);
      }
      catch (IOException ae)
      {
      JOptionPane.showMessageDialog(frame,new String("Error: "+ae));
      }
      }

      public static void main(String[] args)
      {
      new Webbrowser();
      }
      }
      class second implements HyperlinkListener
      {
      private JEditorPane pane;

      public second(JEditorPane pane)
      {
      this.pane = pane;
      }
      public void hyperlinkUpdate(HyperlinkEvent evt)
      {
      if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
      {
      try
      {
      pane.setPage(evt.getURL());
      }
      catch (Exception e){}

      }}}
      public class browser extends javax.swing.JFrame {

      public browser() {
      initComponents();

      }

      // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
      private void initComponents() {
      menuBar = new javax.swing.JMenuBar();
      fileMenu = new javax.swing.JMenu();
      openMenuItem = new javax.swing.JMenuItem();
      saveMenuItem = new javax.swing.JMenuItem();
      saveAsMenuItem = new javax.swing.JMenuItem();
      exitMenuItem = new javax.swing.JMenuItem();
      editMenu = new javax.swing.JMenu();
      cutMenuItem = new javax.swing.JMenuItem();
      copyMenuItem = new javax.swing.JMenuItem();
      pasteMenuItem = new javax.swing.JMenuItem();
      deleteMenuItem = new javax.swing.JMenuItem();
      helpMenu = new javax.swing.JMenu();
      contentsMenuItem = new javax.swing.JMenuItem();
      aboutMenuItem = new javax.swing.JMenuItem();
      setDefaultCloseOperation(javax.swing.WindowConstan ts.EXIT_ON_CLOSE);
      fileMenu.setText("File");
      openMenuItem.setText("Open");
      fileMenu.add(openMenuItem);
      saveMenuItem.setText("Save");
      fileMenu.add(saveMenuItem);
      saveAsMenuItem.setText("Save As ...");
      fileMenu.add(saveAsMenuItem);
      exitMenuItem.setText("Exit");
      exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      exitMenuItemActionPerformed(evt);
      }
      });
      fileMenu.add(exitMenuItem);
      menuBar.add(fileMenu);
      editMenu.setText("Edit");
      cutMenuItem.setText("Cut");
      editMenu.add(cutMenuItem);
      copyMenuItem.setText("Copy");
      editMenu.add(copyMenuItem);
      pasteMenuItem.setText("Paste");
      editMenu.add(pasteMenuItem);
      deleteMenuItem.setText("Delete");
      editMenu.add(deleteMenuItem);
      menuBar.add(editMenu);
      helpMenu.setText("Help");
      contentsMenuItem.setText("Contents");
      helpMenu.add(contentsMenuItem);
      aboutMenuItem.setText("About");
      helpMenu.add(aboutMenuItem);
      menuBar.add(helpMenu);
      setJMenuBar(menuBar);
      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
      getContentPane().setLayout(layout);
      layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
      .addGap(0, 400, Short.MAX_VALUE)
      );
      layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
      .addGap(0, 279, Short.MAX_VALUE)
      );
      pack();
      }// </editor-fold>

      private void exitMenuItemActionPerformed(java.awt.event.ActionE vent evt) {
      System.exit(0);
      }

      public static void main (String args[]) {
      java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
      new browser().setVisible(true);
      Webbrowser wb = new Webbrowser();
      }
      });
      }

      // Variables declaration - do not modify
      private javax.swing.JMenuItem aboutMenuItem;
      private javax.swing.JMenuItem contentsMenuItem;
      private javax.swing.JMenuItem copyMenuItem;
      private javax.swing.JMenuItem cutMenuItem;
      private javax.swing.JMenuItem deleteMenuItem;
      private javax.swing.JMenu editMenu;
      private javax.swing.JMenuItem exitMenuItem;
      private javax.swing.JMenu fileMenu;
      private javax.swing.JMenu helpMenu;
      private javax.swing.JMenuBar menuBar;
      private javax.swing.JMenuItem openMenuItem;
      private javax.swing.JMenuItem pasteMenuItem;
      private javax.swing.JMenuItem saveAsMenuItem;
      private javax.swing.JMenuItem saveMenuItem;
      // End of variables declaration
      }

      Classe SAX:

      public class SAXTreeViewer extends JFrame {
      /** Default parser to use /
      private String vendorParserClass =
      "org.apache.xerces.parsers.SAXParser";
      /
      * The base tree to render /
      private JTree jTree;
      /
      * Tree model to use /
      DefaultTreeModel defaultTreeModel;
      /
      *

      • <p> This initializes the needed Swing settings. </p>
        /
        public SAXTreeViewer() {
        // Handle Swing setup
        super("SAX Tree Viewer");
        setSize(600, 450);
        }
        /
        *
      • <p> This will construct the tree using Swing. </p>
      • @param filename <code>String</code> path to XML document.
        */
        public void init(String xmlURI) throws IOException, SAXException {
        DefaultMutableTreeNode base =
        new DefaultMutableTreeNode("XML Document: " +
        xmlURI);

      // Build the tree model
      defaultTreeModel = new DefaultTreeModel(base);
      jTree = new JTree(defaultTreeModel);
      // Construct the tree hierarchy
      buildTree(defaultTreeModel, base, xmlURI);
      // Display the results
      getContentPane().add(new JScrollPane(jTree),
      BorderLayout.CENTER);
      }
      /**

      • <p>This handles building the Swing UI tree.</p>
      • @param treeModel Swing component to build upon.
      • @param base tree node to build on.
      • @param xmlURI URI to build XML document from.
      • @throws <code>IOException</code> - when reading the XML URI fails.
      • @throws <code>SAXException</code> - when errors in parsing occur.
        /
        public void buildTree(DefaultTreeModel treeModel,
        DefaultMutableTreeNode base, String xmlURI)
        throws IOException, SAXException {
        // Create instances needed for parsing
        XMLReader reader =
        XMLReaderFactory.createXMLReader(vendorParserClass );
        ContentHandler jTreeContentHandler =
        new JTreeContentHandler(treeModel, base);
        ErrorHandler jTreeErrorHandler = new JTreeErrorHandler();
        // Register content handler
        reader.setContentHandler(jTreeContentHandler);
        // Register error handler
        reader.setErrorHandler(jTreeErrorHandler);
        // Parse
        InputSource inputSource =
        new InputSource(xmlURI);
        reader.parse(inputSource);
        }
        /
        *
      • <p> Static entry point for running the viewer. </p>
        /
        public static void main(String[] args) {
        try {
        /

        if (args.length != 1) {
        System.out.println(
        "Usage: java SAXTreeViewer " +
        "[XML Document URI]");
        System.exit(0);
        }*/
        SAXTreeViewer viewer = new SAXTreeViewer();
        //viewer.init(args[0]);
        viewer.init("file.xml");
        viewer.setVisible(true);
        } catch (Exception e) {
        e.printStackTrace();
        }
        }
        }
        /**
      • <b><code>JTreeContentHandler</code></b> implements the SAX
      • <code>ContentHandler</code> interface and defines callback
      • behavior for the SAX callbacks associated with an XML
      • document's content, bulding up JTree nodes.
        /
        class JTreeContentHandler implements ContentHandler {
        /
        * Hold onto the locator for location information /
        private Locator locator;
        /
        * Store URI to prefix mappings /
        private Map namespaceMappings;
        /
        * Tree Model to add nodes to /
        private DefaultTreeModel treeModel;
        /
        * Current node to add sub-nodes to /
        private DefaultMutableTreeNode current;
        /
        *
      • <p> Set up for working with the JTree. </p>
      • @param treeModel tree to add nodes to.
      • @param base node to start adding sub-nodes to.
        /
        public JTreeContentHandler(DefaultTreeModel treeModel,
        DefaultMutableTreeNode base) {
        this.treeModel = treeModel;
        this.current = base;
        this.namespaceMappings = new HashMap();
        }
        /
        *
      • <p>
      • Provide reference to <code>Locator</code> which provides
      • information about where in a document callbacks occur.
      • </p>
      • @param locator <code>Locator</code> object tied to callback
      • process
        /
        public void setDocumentLocator(Locator locator) {
        // Save this for later use
        this.locator = locator;
        }
        /
        *
      • <p>
      • This indicates the start of a Document parse-this precedes
      • all callbacks in all SAX Handlers with the sole exception
      • of <code>{@link #setDocumentLocator}</code>.
      • </p>
      • @throws <code>SAXException</code> when things go wrong
        /
        public void startDocument() throws SAXException {
        // No visual events occur here
        }
        /
        *
      • <p>
      • This indicates the end of a Document parse-this occurs after
      • all callbacks in all SAX Handlers.</code>.
      • </p>
      • @throws <code>SAXException</code> when things go wrong
        /
        public void endDocument() throws SAXException {
        // No visual events occur here
        }
        /
        *
      • <p>
      • This indicates that a processing instruction (other than
      • the XML declaration) has been encountered.
      • </p>
      • @param target <code>String</code> target of PI
      • @param data <code>String</code containing all data sent to the PI.
      • This typically looks like one or more attribute value
      • pairs.
      • @throws <code>SAXException</code> when things go wrong
        /
        public void processingInstruction(String target, String data)
        throws SAXException {
        DefaultMutableTreeNode pi =
        new DefaultMutableTreeNode("PI (target = '" + target +
        "', data = '" + data + "')");
        current.add(pi);
        }
        /
        *
      • <p>
      • This indicates the beginning of an XML Namespace prefix
      • mapping. Although this typically occurs within the root element
      • of an XML document, it can occur at any point within the
      • document. Note that a prefix mapping on an element triggers
      • this callback <i>before</i> the callback for the actual element
      • itself (<code>{@link #startElement}</code>) occurs.
      • </p>
      • @param prefix <code>String</code> prefix used for the namespace
      • being reported
      • @param uri <code>String</code> URI for the namespace
      • being reported
      • @throws <code>SAXException</code> when things go wrong
        /
        public void startPrefixMapping(String prefix, String uri) {
        // No visual events occur here.
        namespaceMappings.put(uri, prefix);
        }
        /
        *
      • <p>
      • This indicates the end of a prefix mapping, when the namespace
      • reported in a <code>{@link #startPrefixMapping}</code> callback
      • is no longer available.
      • </p>
      • @param prefix <code>String</code> of namespace being reported
      • @throws <code>SAXException</code> when things go wrong
        /
        public void endPrefixMapping(String prefix) {
        // No visual events occur here.
        for (Iterator i = namespaceMappings.keySet().iterator();
        i.hasNext(); ) {
        String uri = (String)i.next();
        String thisPrefix = (String)namespaceMappings.get(uri);
        if (prefix.equals(thisPrefix)) {
        namespaceMappings.remove(uri);
        break;
        }
        }
        }
        /
        *
      • <p>
      • This reports the occurrence of an actual element. It includes
      • the element's attributes, with the exception of XML vocabulary
      • specific attributes, such as
      • <code>xmlns:namespace prefix</code> and
      • <code>xsi:schemaLocation</code>.
      • </p>
      • @param namespaceURI <code>String</code> namespace URI this element
      • is associated with, or an empty <code>String</code>
      • @param localName <code>String</code> name of element (with no
      • namespace prefix, if one is present)
      • @param qName <code>String</code> XML 1.0 version of element name:
      • @param atts <code>Attributes</code> list for this element
      • @throws <code>SAXException</code> when things go wrong
        /
        public void startElement(String namespaceURI, String localName,
        String qName, Attributes atts)
        throws SAXException {
        DefaultMutableTreeNode element =
        new DefaultMutableTreeNode("Element: " + localName);
        current.add(element);
        current = element;
        // Determine namespace
        if (namespaceURI.length() > 0) {
        String prefix =
        (String)namespaceMappings.get(namespaceURI);
        if (prefix.equals("")) {
        prefix = "[None]";
        }
        DefaultMutableTreeNode namespace =
        new DefaultMutableTreeNode("Namespace: prefix = '" +
        prefix + "', URI = '" + namespaceURI + "'");
        current.add(namespace);
        }
        // Process attributes
        for (int i=0; i<atts.getLength(); i++) {
        DefaultMutableTreeNode attribute =
        new DefaultMutableTreeNode("Attribute (name = '" +
        atts.getLocalName(i) +
        "', value = '" +
        atts.getValue(i) + "')");
        String attURI = atts.getURI(i);
        if (attURI.length() > 0) {
        String attPrefix =
        (String)namespaceMappings.get(namespaceURI);
        if (attPrefix.equals("")) {
        attPrefix = "[None]";
        }
        DefaultMutableTreeNode attNamespace =
        new DefaultMutableTreeNode("Namespace: prefix = '" +
        attPrefix + "', URI = '" + attURI + "'");
        attribute.add(attNamespace);
        }
        current.add(attribute);
        }
        }
        /
        *
      • <p>
      • Indicates the end of an element
      • (<code></[element name]></code>) is reached. Note that
      • the parser does not distinguish between empty
      • elements and non-empty elements, so this occurs uniformly.
      • </p>
      • @param namespaceURI <code>String</code> URI of namespace this
      • element is associated with
      • @param localName <code>String</code> name of element without prefix
      • @param qName <code>String</code> name of element in XML 1.0 form
      • @throws <code>SAXException</code> when things go wrong
        /
        public void endElement(String namespaceURI, String localName,
        String qName)
        throws SAXException {
        // Walk back up the tree
        current = (DefaultMutableTreeNode)current.getParent();
        }
        /
        *
      • <p>
      • This reports character data (within an element).
      • </p>
      • @param ch <code>char[]</code> character array with character data
      • @param start <code>int</code> index in array where data starts.
      • @param length <code>int</code> index in array where data ends.
      • @throws <code>SAXException</code> when things go wrong
        /
        public void characters(char[] ch, int start, int length)
        throws SAXException {
        String s = new String(ch, start, length);
        DefaultMutableTreeNode data =
        new DefaultMutableTreeNode("Character Data: '" + s + "'");
        current.add(data);
        }
        /
        *
      • <p>
      • This reports whitespace that can be ignored in the
      • originating document. This is typically invoked only when
      • validation is ocurring in the parsing process.
      • </p>
      • @param ch <code>char[]</code> character array with character data
      • @param start <code>int</code> index in array where data starts.
      • @param end <code>int</code> index in array where data ends.
      • @throws <code>SAXException</code> when things go wrong
        */
        public void ignorableWhitespace(char[] ch, int start, int length)
        throws SAXException {

      // This is ignorable, so don't display it
      }
      /**

      • <p>
      • This reports an entity that is skipped by the parser. This
      • should only occur for non-validating parsers, and then is still
      • implementation-dependent behavior.
      • </p>
      • @param name <code>String</code> name of entity being skipped
      • @throws <code>SAXException</code> when things go wrong
        /
        public void skippedEntity(String name) throws SAXException {
        DefaultMutableTreeNode skipped =
        new DefaultMutableTreeNode("Skipped Entity: '" + name + "'");
        current.add(skipped);
        }
        }
        /
        *
      • <b><code>JTreeErrorHandler</code></b> implements the SAX
      • <code>ErrorHandler</code> interface and defines callback
      • behavior for the SAX callbacks associated with an XML
      • document's warnings and errors.
        /
        class JTreeErrorHandler implements ErrorHandler {
        /
        *
      • <p>
      • This will report a warning that has occurred; this indicates
      • that while no XML rules were "broken", something appears
      • to be incorrect or missing.
      • </p>
      • @param exception <code>SAXParseException</code> that occurred.
      • @throws <code>SAXException</code> when things go wrong
        */
        public void warning(SAXParseException exception)
        throws SAXException {

      System.out.println("Parsing Warning\n" +
      " Line: " +
      exception.getLineNumber() + "\n" +
      " URI: " +
      exception.getSystemId() + "\n" +
      " Message: " +
      exception.getMessage());
      throw new SAXException("Warning encountered");
      }
      /**

      • <p>
      • This will report an error that has occurred; this indicates
      • that a rule was broken, typically in validation, but that
      • parsing can reasonably continue.
      • </p>
      • @param exception <code>SAXParseException</code> that occurred.
      • @throws <code>SAXException</code> when things go wrong
        */
        public void error(SAXParseException exception)
        throws SAXException {

      System.out.println("Parsing Error\n" +
      " Line: " +
      exception.getLineNumber() + "\n" +
      " URI: " +
      exception.getSystemId() + "\n" +
      " Message: " +
      exception.getMessage());
      throw new SAXException("Error encountered");
      }
      /**

      • <p>
      • This will report a fatal error that has occurred; this indicates
      • that a rule has been broken that makes continued parsing either
      • impossible or an almost certain waste of time.
      • </p>
      • @param exception <code>SAXParseException</code> that occurred.
      • @throws <code>SAXException</code> when things go wrong
        */
        public void fatalError(SAXParseException exception)
        throws SAXException {

      System.out.println("Parsing Fatal Error\n" +
      " Line: " +
      exception.getLineNumber() + "\n" +
      " URI: " +
      exception.getSystemId() + "\n" +
      " Message: " +
      exception.getMessage());
      throw new SAXException("Fatal Error encountered");
      }
      }

      Come implemento le due classi?

      postato in Coding
      C
      chicco80
    • Implementazione parser

      Salve a tutti,
      ho un (piccolo) problema: ho realizzato un browser in java e dovrei eseguire il parsing di file xml. Per il parsing utilizzo la classe SAXTreeViewer, ma non riesco a implementarla nel codice browser. Sapreste darmi una mano?
      grazie

      browser:

      class Webbrowser implements ActionListener
      {
      JTextField t1;
      JLabel l1;
      JButton b1;
      GridBagLayout gbl;
      GridBagConstraints gbc;
      JPanel p;
      JFrame frame;
      JScrollPane scrollPane;
      JEditorPane jep;
      static String initialPage;

      public Webbrowser()
      {
      //JFrame.setDefaultLookAndFeelDecorated(true);
      /try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
      }
      catch(Exception e)
      {
      e.printStackTrace();
      }
      /
      frame=new JFrame("Chicco's Web Browser");

      gbl=new GridBagLayout();
      gbc=new GridBagConstraints();

      p=new JPanel();
      p.setLayout(gbl);

      jep = new JEditorPane();

      t1=new JTextField();

      b1=new JButton("Trova");
      b1.addActionListener(this);
      frame.getRootPane().setDefaultButton(b1);

      l1=new JLabel("Indirizzo");

      gbc.anchor=GridBagConstraints.NORTHEAST;
      gbc.fill=GridBagConstraints.HORIZONTAL;
      gbc.gridx=0;
      gbc.gridy=0;
      gbc.weightx=0.0;
      gbl.setConstraints(l1,gbc);
      p.add(l1);

      gbc.anchor=GridBagConstraints.NORTHEAST;
      gbc.gridx=1;
      gbc.gridy=0;
      gbc.weightx=1.0;
      gbl.setConstraints(t1,gbc);
      p.add(t1);

      gbc.anchor=GridBagConstraints.NORTHWEST;
      gbc.gridx=2;
      gbc.gridy=0;
      gbc.weightx=0.0;
      gbl.setConstraints(b1,gbc);
      p.add(b1);

      scrollPane = new JScrollPane(jep);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      
      frame.getContentPane().add(p,BorderLayout.NORTH);
      

      frame.getContentPane().add(scrollPane);
      frame.setSize(1000,700);
      frame.setVisible(true);
      }

      public void actionPerformed(ActionEvent e)
      {
      initialPage=t1.getText();
      char a=initialPage.charAt(0);
      char b=initialPage.charAt(1);
      char c=initialPage.charAt(2);
      char d=initialPage.charAt(3);
      char ea=initialPage.charAt(4);
      char f=initialPage.charAt(5);
      char g=initialPage.charAt(6);

      if((a=='h')&&(b=='t')&&(c=='t')&&(d=='p')&&(ea==':')&&(f=='/')&&(g=='/'))
      {
      initialPage=t1.getText();
      }
      else
      {
      initialPage="<A href="http://"+initialPage">http://"+initialPage;
      }
      jep.setEditable(false);
      jep.addHyperlinkListener(new second(jep));
      try
      {
      jep.setPage(initialPage);
      }
      catch (IOException ae)
      {
      JOptionPane.showMessageDialog(frame,new String("Error: "+ae));
      }
      }

      public static void main(String[] args)
      {
      new Webbrowser();
      }
      }
      class second implements HyperlinkListener
      {
      private JEditorPane pane;

      public second(JEditorPane pane)
      {
      this.pane = pane;
      }
      public void hyperlinkUpdate(HyperlinkEvent evt)
      {
      if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
      {
      try
      {
      pane.setPage(evt.getURL());
      }
      catch (Exception e){}

      }}}
      public class browser extends javax.swing.JFrame {

      public browser() {
          initComponents();
          
      }
      
      
      // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                          
      private void initComponents() {
          menuBar = new javax.swing.JMenuBar();
          fileMenu = new javax.swing.JMenu();
          openMenuItem = new javax.swing.JMenuItem();
          saveMenuItem = new javax.swing.JMenuItem();
          saveAsMenuItem = new javax.swing.JMenuItem();
          exitMenuItem = new javax.swing.JMenuItem();
          editMenu = new javax.swing.JMenu();
          cutMenuItem = new javax.swing.JMenuItem();
          copyMenuItem = new javax.swing.JMenuItem();
          pasteMenuItem = new javax.swing.JMenuItem();
          deleteMenuItem = new javax.swing.JMenuItem();
          helpMenu = new javax.swing.JMenu();
          contentsMenuItem = new javax.swing.JMenuItem();
          aboutMenuItem = new javax.swing.JMenuItem();
          setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
          fileMenu.setText("File");
          openMenuItem.setText("Open");
          fileMenu.add(openMenuItem);
          saveMenuItem.setText("Save");
          fileMenu.add(saveMenuItem);
          saveAsMenuItem.setText("Save As ...");
          fileMenu.add(saveAsMenuItem);
          exitMenuItem.setText("Exit");
          exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent evt) {
                  exitMenuItemActionPerformed(evt);
              }
          });
          fileMenu.add(exitMenuItem);
          menuBar.add(fileMenu);
          editMenu.setText("Edit");
          cutMenuItem.setText("Cut");
          editMenu.add(cutMenuItem);
          copyMenuItem.setText("Copy");
          editMenu.add(copyMenuItem);
          pasteMenuItem.setText("Paste");
          editMenu.add(pasteMenuItem);
          deleteMenuItem.setText("Delete");
          editMenu.add(deleteMenuItem);
          menuBar.add(editMenu);
          helpMenu.setText("Help");
          contentsMenuItem.setText("Contents");
          helpMenu.add(contentsMenuItem);
          aboutMenuItem.setText("About");
          helpMenu.add(aboutMenuItem);
          menuBar.add(helpMenu);
          setJMenuBar(menuBar);
          javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
          getContentPane().setLayout(layout);
          layout.setHorizontalGroup(
              layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGap(0, 400, Short.MAX_VALUE)
          );
          layout.setVerticalGroup(
              layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGap(0, 279, Short.MAX_VALUE)
          );
          pack();
      }// </editor-fold>                        
      
      
      private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                             
          System.exit(0);
      }                                            
      
      
      
          public static void main (String args[]) {
           java.awt.EventQueue.invokeLater(new Runnable() {
              public void run() {
                  new browser().setVisible(true);
                  Webbrowser wb = new Webbrowser();             
              }
          }); 
      }
          
      // Variables declaration - do not modify                     
      private javax.swing.JMenuItem aboutMenuItem;
      private javax.swing.JMenuItem contentsMenuItem;
      private javax.swing.JMenuItem copyMenuItem;
      private javax.swing.JMenuItem cutMenuItem;
      private javax.swing.JMenuItem deleteMenuItem;
      private javax.swing.JMenu editMenu;
      private javax.swing.JMenuItem exitMenuItem;
      private javax.swing.JMenu fileMenu;
      private javax.swing.JMenu helpMenu;
      private javax.swing.JMenuBar menuBar;
      private javax.swing.JMenuItem openMenuItem;
      private javax.swing.JMenuItem pasteMenuItem;
      private javax.swing.JMenuItem saveAsMenuItem;
      private javax.swing.JMenuItem saveMenuItem;
      // End of variables declaration                   
      

      }

      Classe SAX:

      public class SAXTreeViewer extends JFrame {
      /** Default parser to use /
      private String vendorParserClass =
      "org.apache.xerces.parsers.SAXParser";
      /
      * The base tree to render /
      private JTree jTree;
      /
      * Tree model to use /
      DefaultTreeModel defaultTreeModel;
      /
      *
      * <p> This initializes the needed Swing settings. </p>
      /
      public SAXTreeViewer() {
      // Handle Swing setup
      super("SAX Tree Viewer");
      setSize(600, 450);
      }
      /
      *
      * <p> This will construct the tree using Swing. </p>
      *
      * @param filename <code>String</code> path to XML document.
      */
      public void init(String xmlURI) throws IOException, SAXException {
      DefaultMutableTreeNode base =
      new DefaultMutableTreeNode("XML Document: " +
      xmlURI);

          // Build the tree model
          defaultTreeModel = new DefaultTreeModel(base);
          jTree = new JTree(defaultTreeModel);
          // Construct the tree hierarchy
          buildTree(defaultTreeModel, base, xmlURI);
          // Display the results
          getContentPane().add(new JScrollPane(jTree), 
              BorderLayout.CENTER);
      }
      /**
       * <p>This handles building the Swing UI tree.</p>
       *
       * @param treeModel Swing component to build upon.
       * @param base tree node to build on.
       * @param xmlURI URI to build XML document from.
       * @throws <code>IOException</code> - when reading the XML URI fails.
       * @throws <code>SAXException</code> - when errors in parsing occur.
       */
      public void buildTree(DefaultTreeModel treeModel, 
                            DefaultMutableTreeNode base, String xmlURI) 
          throws IOException, SAXException {
          // Create instances needed for parsing
          XMLReader reader = 
              XMLReaderFactory.createXMLReader(vendorParserClass);
          ContentHandler jTreeContentHandler = 
              new JTreeContentHandler(treeModel, base);
          ErrorHandler jTreeErrorHandler = new JTreeErrorHandler();
          // Register content handler
          reader.setContentHandler(jTreeContentHandler);
          // Register error handler
          reader.setErrorHandler(jTreeErrorHandler);
          // Parse
          InputSource inputSource = 
              new InputSource(xmlURI);
          reader.parse(inputSource);
      }
      /**
       * <p> Static entry point for running the viewer. </p>
       */
      public static void main(String[] args) {
          try {
              /*
               if (args.length != 1) {
                  System.out.println(
                      "Usage: java SAXTreeViewer " +
                      "[XML Document URI]");
                  System.exit(0);
              }*/
              SAXTreeViewer viewer = new SAXTreeViewer();
              //viewer.init(args[0]);
              viewer.init("[file.xml](http://www.freeitaly.it/gadget.xml)");
              viewer.setVisible(true);
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
      

      }
      /**

      • <b><code>JTreeContentHandler</code></b> implements the SAX
      • <code>ContentHandler</code> interface and defines callback
      • behavior for the SAX callbacks associated with an XML
      • document's content, bulding up JTree nodes.
        /
        class JTreeContentHandler implements ContentHandler {
        /
        * Hold onto the locator for location information /
        private Locator locator;
        /
        * Store URI to prefix mappings /
        private Map namespaceMappings;
        /
        * Tree Model to add nodes to /
        private DefaultTreeModel treeModel;
        /
        * Current node to add sub-nodes to /
        private DefaultMutableTreeNode current;
        /
        *
        • <p> Set up for working with the JTree. </p>
        • @param treeModel tree to add nodes to.
        • @param base node to start adding sub-nodes to.
          /
          public JTreeContentHandler(DefaultTreeModel treeModel,
          DefaultMutableTreeNode base) {
          this.treeModel = treeModel;
          this.current = base;
          this.namespaceMappings = new HashMap();
          }
          /
          *
        • <p>
        • Provide reference to <code>Locator</code> which provides
        • information about where in a document callbacks occur.
        • </p>
        • @param locator <code>Locator</code> object tied to callback
        •    process
          
        /
        public void setDocumentLocator(Locator locator) {
        // Save this for later use
        this.locator = locator;
        }
        /
        *
        • <p>

        • This indicates the start of a Document parse-this precedes

        • all callbacks in all SAX Handlers with the sole exception

        • of <code>{@link #setDocumentLocator}</code>.

        • </p>

        • @throws <code>SAXException</code> when things go wrong
          /
          public void startDocument() throws SAXException {
          // No visual events occur here
          }
          /
          *

        • <p>

        • This indicates the end of a Document parse-this occurs after

        • all callbacks in all SAX Handlers.</code>.

        • </p>

        • @throws <code>SAXException</code> when things go wrong
          /
          public void endDocument() throws SAXException {
          // No visual events occur here
          }
          /
          *

        • <p>

        • This indicates that a processing instruction (other than

        • the XML declaration) has been encountered.
          
        • </p>

        • @param target <code>String</code> target of PI

        • @param data <code>String</code containing all data sent to the PI.

        •           This typically looks like one or more attribute value
          
        •           pairs.
          
        • @throws <code>SAXException</code> when things go wrong
          /
          public void processingInstruction(String target, String data)
          throws SAXException {
          DefaultMutableTreeNode pi =
          new DefaultMutableTreeNode("PI (target = '" + target +
          "', data = '" + data + "')");
          current.add(pi);
          }
          /
          *

        • <p>

        • This indicates the beginning of an XML Namespace prefix

        • mapping. Although this typically occurs within the root element
          
        • of an XML document, it can occur at any point within the
          
        • document. Note that a prefix mapping on an element triggers
          
        • this callback <i>before</i> the callback for the actual element
          
        • itself (<code>{@link #startElement}</code>) occurs.
          
        • </p>

        • @param prefix <code>String</code> prefix used for the namespace

        •            being reported
          
        • @param uri <code>String</code> URI for the namespace

        •           being reported
          
        • @throws <code>SAXException</code> when things go wrong
          /
          public void startPrefixMapping(String prefix, String uri) {
          // No visual events occur here.
          namespaceMappings.put(uri, prefix);
          }
          /
          *

        • <p>

        • This indicates the end of a prefix mapping, when the namespace

        • reported in a <code>{@link #startPrefixMapping}</code> callback
          
        • is no longer available.
          
        • </p>

        • @param prefix <code>String</code> of namespace being reported

        • @throws <code>SAXException</code> when things go wrong
          /
          public void endPrefixMapping(String prefix) {
          // No visual events occur here.
          for (Iterator i = namespaceMappings.keySet().iterator();
          i.hasNext(); ) {
          String uri = (String)i.next();
          String thisPrefix = (String)namespaceMappings.get(uri);
          if (prefix.equals(thisPrefix)) {
          namespaceMappings.remove(uri);
          break;
          }
          }
          }
          /
          *

        • <p>

        • This reports the occurrence of an actual element. It includes

        • the element's attributes, with the exception of XML vocabulary
          
        • specific attributes, such as
          
        • <code>xmlns:[namespace prefix]</code> and
          
        • <code>xsi:schemaLocation</code>.
          
        • </p>

        • @param namespaceURI <code>String</code> namespace URI this element

        •           is associated with, or an empty <code>String</code>
          
        • @param localName <code>String</code> name of element (with no

        •           namespace prefix, if one is present)
          
        • @param qName <code>String</code> XML 1.0 version of element name:

        •            [namespace prefix]:[localName]
          
        • @param atts <code>Attributes</code> list for this element

        • @throws <code>SAXException</code> when things go wrong
          /
          public void startElement(String namespaceURI, String localName,
          String qName, Attributes atts)
          throws SAXException {
          DefaultMutableTreeNode element =
          new DefaultMutableTreeNode("Element: " + localName);
          current.add(element);
          current = element;
          // Determine namespace
          if (namespaceURI.length() > 0) {
          String prefix =
          (String)namespaceMappings.get(namespaceURI);
          if (prefix.equals("")) {
          prefix = "[None]";
          }
          DefaultMutableTreeNode namespace =
          new DefaultMutableTreeNode("Namespace: prefix = '" +
          prefix + "', URI = '" + namespaceURI + "'");
          current.add(namespace);
          }
          // Process attributes
          for (int i=0; i<atts.getLength(); i++) {
          DefaultMutableTreeNode attribute =
          new DefaultMutableTreeNode("Attribute (name = '" +
          atts.getLocalName(i) +
          "', value = '" +
          atts.getValue(i) + "')");
          String attURI = atts.getURI(i);
          if (attURI.length() > 0) {
          String attPrefix =
          (String)namespaceMappings.get(namespaceURI);
          if (attPrefix.equals("")) {
          attPrefix = "[None]";
          }
          DefaultMutableTreeNode attNamespace =
          new DefaultMutableTreeNode("Namespace: prefix = '" +
          attPrefix + "', URI = '" + attURI + "'");
          attribute.add(attNamespace);
          }
          current.add(attribute);
          }
          }
          /
          *

        • <p>

        • Indicates the end of an element

        • (<code>&lt;/[element name]&gt;</code>) is reached. Note that
          
        • the parser does not distinguish between empty
          
        • elements and non-empty elements, so this occurs uniformly.
          
        • </p>

        • @param namespaceURI <code>String</code> URI of namespace this

        •            element is associated with
          
        • @param localName <code>String</code> name of element without prefix

        • @param qName <code>String</code> name of element in XML 1.0 form

        • @throws <code>SAXException</code> when things go wrong
          /
          public void endElement(String namespaceURI, String localName,
          String qName)
          throws SAXException {
          // Walk back up the tree
          current = (DefaultMutableTreeNode)current.getParent();
          }
          /
          *

        • <p>

        • This reports character data (within an element).

        • </p>

        • @param ch <code>char[]</code> character array with character data

        • @param start <code>int</code> index in array where data starts.

        • @param length <code>int</code> index in array where data ends.

        • @throws <code>SAXException</code> when things go wrong
          /
          public void characters(char[] ch, int start, int length)
          throws SAXException {
          String s = new String(ch, start, length);
          DefaultMutableTreeNode data =
          new DefaultMutableTreeNode("Character Data: '" + s + "'");
          current.add(data);
          }
          /
          *

        • <p>

        • This reports whitespace that can be ignored in the

        • originating document. This is typically invoked only when

        • validation is ocurring in the parsing process.

        • </p>

        • @param ch <code>char[]</code> character array with character data

        • @param start <code>int</code> index in array where data starts.

        • @param end <code>int</code> index in array where data ends.

        • @throws <code>SAXException</code> when things go wrong
          */
          public void ignorableWhitespace(char[] ch, int start, int length)
          throws SAXException {

          // This is ignorable, so don't display it
          }
          /**

        • <p>

        • This reports an entity that is skipped by the parser. This

        • should only occur for non-validating parsers, and then is still
          
        • implementation-dependent behavior.
          
        • </p>

        • @param name <code>String</code> name of entity being skipped

        • @throws <code>SAXException</code> when things go wrong
          /
          public void skippedEntity(String name) throws SAXException {
          DefaultMutableTreeNode skipped =
          new DefaultMutableTreeNode("Skipped Entity: '" + name + "'");
          current.add(skipped);
          }
          }
          /
          *

      • <b><code>JTreeErrorHandler</code></b> implements the SAX
      • <code>ErrorHandler</code> interface and defines callback
      • behavior for the SAX callbacks associated with an XML
      • document's warnings and errors.
        /
        class JTreeErrorHandler implements ErrorHandler {
        /
        *
        • <p>

        • This will report a warning that has occurred; this indicates

        • that while no XML rules were "broken", something appears

        • to be incorrect or missing.

        • </p>

        • @param exception <code>SAXParseException</code> that occurred.

        • @throws <code>SAXException</code> when things go wrong
          */
          public void warning(SAXParseException exception)
          throws SAXException {

          System.out.println("Parsing Warning\n" +
          " Line: " +
          exception.getLineNumber() + "\n" +
          " URI: " +
          exception.getSystemId() + "\n" +
          " Message: " +
          exception.getMessage());
          throw new SAXException("Warning encountered");
          }
          /**

        • <p>

        • This will report an error that has occurred; this indicates

        • that a rule was broken, typically in validation, but that

        • parsing can reasonably continue.

        • </p>

        • @param exception <code>SAXParseException</code> that occurred.

        • @throws <code>SAXException</code> when things go wrong
          */
          public void error(SAXParseException exception)
          throws SAXException {

          System.out.println("Parsing Error\n" +
          " Line: " +
          exception.getLineNumber() + "\n" +
          " URI: " +
          exception.getSystemId() + "\n" +
          " Message: " +
          exception.getMessage());
          throw new SAXException("Error encountered");
          }
          /**

        • <p>

        • This will report a fatal error that has occurred; this indicates

        • that a rule has been broken that makes continued parsing either

        • impossible or an almost certain waste of time.

        • </p>

        • @param exception <code>SAXParseException</code> that occurred.

        • @throws <code>SAXException</code> when things go wrong
          */
          public void fatalError(SAXParseException exception)
          throws SAXException {

          System.out.println("Parsing Fatal Error\n" +
          " Line: " +
          exception.getLineNumber() + "\n" +
          " URI: " +
          exception.getSystemId() + "\n" +
          " Message: " +
          exception.getMessage());
          throw new SAXException("Fatal Error encountered");
          }
          }

      Dove colloco SAXTreeViewer nel browser?

      postato in Presentati alla Community
      C
      chicco80