All pastes #834728 Raw Edit

Someone

public text v1 · immutable
#834728 ·published 2007-12-28 12:39 UTC
rendered paste body
/*
 * Browser.java
 *
 * Created on December 28, 2007, 1:39 PM
 *
 *Search is not working
 *Refresh is not working
 *how to implement Stop?
 *Back doesnt get updated when we click a hyperlink
 *
 *
 *
 
 */

package webbrowser;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.html.*;
import javax.swing.text.*;
import java.net.*;
import java.io.*;
import java.util.*;

public class Browser extends JFrame implements HyperlinkListener {
    
    /** Creates new form Browser */
    public Browser() {
        initComponents();
        try {
            showPage(new URL(Home), true);
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
    }
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                          
    private void initComponents() {
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        JPTop = new javax.swing.JPanel();
        JPMB = new javax.swing.JPanel();
        JBBack = new javax.swing.JButton();
        JBForward = new javax.swing.JButton();
        JBStop = new javax.swing.JButton();
        JBRefresh = new javax.swing.JButton();
        JBHome = new javax.swing.JButton();
        JBMarkHome = new javax.swing.JButton();
        Main = new javax.swing.JPanel();
        JLURL = new javax.swing.JLabel();
        JTURL = new javax.swing.JTextField();
        JBGo = new javax.swing.JButton();
        JTSearch = new javax.swing.JTextField();
        JBSearch = new javax.swing.JButton();
        JPCenterPage = new javax.swing.JPanel();
        JSPPage = new javax.swing.JScrollPane();
        JEPPage = new javax.swing.JEditorPane();
        jLabel1 = new javax.swing.JLabel();

        jMenu1.setText("Menu");
        jMenuBar1.add(jMenu1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("JBrowser!");
        setMinimumSize(new java.awt.Dimension(640, 480));
        JPTop.setLayout(new java.awt.BorderLayout(5, 5));

        JBBack.setText("< Back");
        JBBack.setToolTipText("Takes you to the last page visited");
        JBBack.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBBackActionPerformed(evt);
            }
        });

        JPMB.add(JBBack);

        JBForward.setText("Forward >");
        JBForward.setToolTipText("Takes you one step forward, to the page where you were before you pessed Back");
        JBForward.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBForwardActionPerformed(evt);
            }
        });

        JPMB.add(JBForward);

        JBStop.setText("Stop");
        JBStop.setToolTipText("Stops loading current page");
        JPMB.add(JBStop);

        JBRefresh.setText("Refresh");
        JBRefresh.setToolTipText("Refreshes the current page");
        JBRefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBRefreshActionPerformed(evt);
            }
        });

        JPMB.add(JBRefresh);

        JBHome.setText("Home");
        JBHome.setToolTipText("Takes you to the homepage");
        JBHome.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBHomeActionPerformed(evt);
            }
        });

        JPMB.add(JBHome);

        JBMarkHome.setText("Mark Home");
        JBMarkHome.setToolTipText("Changes your Home to the current URL in the AddressBar");
        JBMarkHome.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBMarkHomeActionPerformed(evt);
            }
        });

        JPMB.add(JBMarkHome);

        JPTop.add(JPMB, java.awt.BorderLayout.NORTH);

        JLURL.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        JLURL.setText("URL:");
        Main.add(JLURL);

        JTURL.setColumns(22);
        JTURL.setToolTipText("Please enter the desired URL here.");
        JTURL.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JTURLActionPerformed(evt);
            }
        });

        Main.add(JTURL);

        JBGo.setText("GO!");
        JBGo.setToolTipText("Click to show the desired URL");
        JBGo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBGoActionPerformed(evt);
            }
        });

        Main.add(JBGo);

        JTSearch.setColumns(10);
        JTSearch.setText("Search Google");
        JTSearch.setToolTipText("Enter the text that you want to serach");
        JTSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JTSearchActionPerformed(evt);
            }
        });

        Main.add(JTSearch);

        JBSearch.setText("Search");
        JBSearch.setToolTipText("Click to serach for what you entered");
        JBSearch.setActionCommand("JBSearch");
        JBSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBSearchActionPerformed(evt);
            }
        });

        Main.add(JBSearch);

        JPTop.add(Main, java.awt.BorderLayout.SOUTH);

        getContentPane().add(JPTop, java.awt.BorderLayout.NORTH);

        JPCenterPage.setLayout(new java.awt.BorderLayout(5, 5));

        JSPPage.setToolTipText("");
        JEPPage.setEditable(false);
        JEPPage.setToolTipText("You should see the resulting page here");
        JEPPage.setDoubleBuffered(true);
        JEPPage.addHyperlinkListener(this);
        JSPPage.setViewportView(JEPPage);

        JPCenterPage.add(JSPPage, java.awt.BorderLayout.CENTER);

        jLabel1.setText(" ");
        JPCenterPage.add(jLabel1, java.awt.BorderLayout.SOUTH);

        getContentPane().add(JPCenterPage, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>                        

    private void JTSearchActionPerformed(java.awt.event.ActionEvent evt) {                                         
// TODO add your handling code here:
        search(JTSearch.getText());
    }                                        

    private void JBSearchActionPerformed(java.awt.event.ActionEvent evt) {                                         
// TODO add your handling code here:
        search(JTSearch.getText());
    }                                        
    
    private void JBRefreshActionPerformed(java.awt.event.ActionEvent evt) {                                          
// TODO add your handling code here:
        URL currentUrl = JEPPage.getPage();
        showPage(currentUrl,false);
        
    }                                         
    
    private void JBBackActionPerformed(java.awt.event.ActionEvent evt) {                                       
// TODO add your handling code here:
        URL currentUrl = JEPPage.getPage();
        int pageIndex = pageList.indexOf(currentUrl.toString());
        try {
            showPage(new URL((String) pageList.get(pageIndex - 1)), false);
        } catch (Exception e) {}
    }                                      
    
    private void JBForwardActionPerformed(java.awt.event.ActionEvent evt) {                                          
// TODO add your handling code here:
        URL currentUrl = JEPPage.getPage();
        int pageIndex = pageList.indexOf(currentUrl.toString());
        try {
            showPage(new URL((String) pageList.get(pageIndex + 1)), false);
        } catch (Exception e) {}
    }                                         
    
    private void JBMarkHomeActionPerformed(java.awt.event.ActionEvent evt) {                                           
// TODO add your handling code here:
        Home=JTURL.getText();
    }                                          
    
    private void JBHomeActionPerformed(java.awt.event.ActionEvent evt) {                                       
        try {
// TODO add your handling code here:
            showPage(new URL(Home), true);
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
    }                                      
    
    private void JBGoActionPerformed(java.awt.event.ActionEvent evt) {                                     
// TODO add your handling code here:
        URL verifiedUrl = verifyUrl(JTURL.getText());
        if (verifiedUrl != null) {
            showPage(verifiedUrl, true);
        } else {
            showError("Invalid URL");
        }
    }                                    
    
    
    
    private void search(String s)
    {
        
        s="http://www.google.com/search?q="+s;
        System.out.println("Searching for " + s);
        URL search;
        try {
            search = new URL(s);
            showPage(search,true);
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
            showError("Could not search");
        }
        
        
    }
    
    // Show dialog box with error message.
    private void showError(String errorMessage) {
        JOptionPane.showMessageDialog(this, errorMessage,
                "Critical Error", JOptionPane.ERROR_MESSAGE);
    }
    
    // Verify URL format.
    private URL verifyUrl(String url) {
        // Only allow HTTP and FILE URLs.
        if (!(url.toLowerCase().startsWith("http://") || url.toLowerCase().startsWith("file:/")))
            return null;
        
        // Verify format of URL.
        URL verifiedUrl = null;
        try {
            verifiedUrl = new URL(url);
        } catch (Exception e) {
            return null;
        }
        
        return verifiedUrl;
    }
    
    
    
    private void JTURLActionPerformed(java.awt.event.ActionEvent evt) {                                      
// TODO add your handling code here:
        URL verifiedUrl = verifyUrl(JTURL.getText());
        if (verifiedUrl != null) {
            showPage(verifiedUrl, true);
        } else {
            showError("Invalid URL");
        }
        
    }                                     
    
    
    /* Show the specified page and add it to
     the page list if specified. */
    private void showPage(URL pageUrl, boolean addToList) {
        // Show hour glass cursor while crawling is under way.
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        
        try {
            // Get URL of page currently being displayed.
            URL currentUrl = JEPPage.getPage();
            
            // Load and display specified page.
            JEPPage.setPage(pageUrl);
            
            // Get URL of new page being displayed.
            URL newUrl = JEPPage.getPage();
            
            // Add page to list if specified.
            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());
            }
            
            // Update location text field with URL of current page.
            JTURL.setText(newUrl.toString());
            
            // Update buttons based on the page being displayed.
            updateButtons();
        } catch (Exception e) {
            // Show error messsage.
            showError("Unable to load page : " + pageUrl.toString());
        } finally {
            // Return to default cursor.
            setCursor(Cursor.getDefaultCursor());
        }
    }
    
  /* Update back and forward buttons based on
     the page being displayed. */
    private void updateButtons() {
        if (pageList.size() < 2) {
            JBBack.setEnabled(false);
            JBForward.setEnabled(false);
        } else {
            URL currentUrl = JEPPage.getPage();
            int pageIndex = pageList.indexOf(currentUrl.toString());
            JBBack.setEnabled(pageIndex > 0);
            JBForward.setEnabled(pageIndex < (pageList.size() - 1));
        }
    }
    
    // Handle hyperlink's being clicked.
    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) JEPPage.getDocument();
                document.processHTMLFrameHyperlinkEvent(linkEvent);
            } else {
                showPage(event.getURL(), true);
            }
        }
    }
    
    
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Browser().setVisible(true);
            }
        });
    }
    
    
    // Variables declaration - do not modify                     
    private javax.swing.JButton JBBack;
    private javax.swing.JButton JBForward;
    private javax.swing.JButton JBGo;
    private javax.swing.JButton JBHome;
    private javax.swing.JButton JBMarkHome;
    private javax.swing.JButton JBRefresh;
    private javax.swing.JButton JBSearch;
    private javax.swing.JButton JBStop;
    private javax.swing.JEditorPane JEPPage;
    private javax.swing.JLabel JLURL;
    private javax.swing.JPanel JPCenterPage;
    private javax.swing.JPanel JPMB;
    private javax.swing.JPanel JPTop;
    private javax.swing.JScrollPane JSPPage;
    private javax.swing.JTextField JTSearch;
    private javax.swing.JTextField JTURL;
    private javax.swing.JPanel Main;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    // End of variables declaration                   
    private static String Home="http://localhost/xampp";
    private ArrayList pageList = new ArrayList();
}