Skip to content

Instantly share code, notes, and snippets.

@WillWetzelCMS
Last active September 29, 2018 11:51
Show Gist options
  • Save WillWetzelCMS/08da24b0d8c42083f189a8525af8fb0f to your computer and use it in GitHub Desktop.
Save WillWetzelCMS/08da24b0d8c42083f189a8525af8fb0f to your computer and use it in GitHub Desktop.
CSC1022 - Final Web Browser
http://www.ncl.ac.uk/computing/#
/* Name: Will Wetzel - 130251255
* Program: Creating a Web browser - File Menu.
* Module: CSC1022 - Programming II
* Description: This program will create a JMenuBar, with all the features required for permanent history and permanent bookmarks
* and return the JMenuBar to the caller.
*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import javax.swing.JEditorPane;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
public class FileMenu{
JEditorPane editorPane;
ToolBarMain toolBar;
public JMenuBar CreateFileMenu(JEditorPane editorPane, ToolBarMain toolBar){
this.editorPane = editorPane;
this.toolBar = toolBar;
JMenuBar menuBar = new JMenuBar();
// ***** Adding a menu. ****** //
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
// ***** Adding browser history and options. ****** //
JMenuItem menuItemHistory = new JMenuItem("Show History"); //New item to show history.
menuItemHistory.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){ //When clicked, read from History file using "HomeWriter" class.
String fileLocation = "History.txt"; //File location of config file.
HomeReader historyFile = new HomeReader(fileLocation);
StringBuilder History = historyFile.ReadFile(); //Store in String builder.
editorPane.setText(History.toString()); //Set text of editorPane.
}
});
fileMenu.add(menuItemHistory); //Add button to menu (File menu).
JMenuItem menuItemHistoryClear = new JMenuItem("Clear History"); //New item to clear history.
menuItemHistoryClear.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){ //When clicked, use HomeWriter class to rewrite the file.
String fileLocation = "History.txt"; //File location of config file.
HomeWriter historyFileClear = new HomeWriter(fileLocation, false); //New HOmewriter with appendToFile set to false.
historyFileClear.writeToFile(""); //Write a blank space.
toolBar.clearHistory(); //Clear back/forward history too.
toolBar.goHome(true); //Go to home page of editorPane.
}
});
fileMenu.add(menuItemHistoryClear); //Add to File menu.
// ***** Creating a sub menu for bookmarks. ***** //
fileMenu.addSeparator(); //Add separator for aethstetics.
JMenu bookmarkSubmenu = new JMenu("Bookmarks"); //New submenu for Bookmarks.
loadBookmarks(bookmarkSubmenu); //Call method to load bookmarks from Bookmark text file.
fileMenu.add(bookmarkSubmenu); //Add to the File menu.
JMenuItem menuItemAddtoBookmarks = new JMenuItem("Add to Bookmarks"); //New button, add to bookmarks.
menuItemAddtoBookmarks.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event) { //When clicked, create a new bookmark and add to submenu.
JMenuItem newBookmark = new JMenuItem(); //If newBookmark is not null then
newBookmark = addBookmarks(); //Add bookmark to submenu.
if(newBookmark != null) //If newBookmark is not null then
loadBookmarks(bookmarkSubmenu); //Reload submenu of bookmarks (update).
}
});
fileMenu.add(menuItemAddtoBookmarks); //Add to File menu.
JMenuItem menuItemRemoveBookmark = new JMenuItem("Remove page from Bookmarks");
menuItemRemoveBookmark.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
URL currentUrl = editorPane.getPage();
String[] bookmarksArray = getBookmarks();
if(Arrays.asList(bookmarksArray). contains(currentUrl.toString())){
removeBookmark();
loadBookmarks(bookmarkSubmenu);
} else{
JOptionPane.showMessageDialog(null, "This page isn't a bookmark", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
fileMenu.add(menuItemRemoveBookmark);
fileMenu.addSeparator(); //Add separator for aethstetics.
JMenuItem menuItemExit = new JMenuItem("Exit"); //New button to close browser.
menuItemExit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){ //When clicked, call exit method to close browser.
exit();
}
});
fileMenu.add(menuItemExit); //Add to File menu.
return menuBar; //Return menuBar to WebPaneMain class to add onto JFrame.
}
private void exit(){ //Method for closing browser from within the browser.
System.exit(0);
}
private String[] getBookmarks(){ //Method for getting bookmark String array.
String fileLocation = "Bookmarks.txt"; //File location of config file.
HomeReader bookmarksFile = new HomeReader(fileLocation); //Create instance of file reader for bookmark file.
StringBuilder bookmarks = bookmarksFile.ReadFile(); //Store in String builder.
String[] bookmarksArray = bookmarks.toString().replaceAll("<br>", " ").split(" "); //Convert String builder to array while splitting the strings.
return bookmarksArray; //Return string[] of bookmarks.
}
private JMenu loadBookmarks(JMenu bookmarkSubmenu){ //Method for loading bookmarks from text file.
String[] bookmarksArray = getBookmarks(); //Get array of Strings of bookmarks.
bookmarkSubmenu.removeAll(); //Empty the submenu.
for(int i = 0; i < bookmarksArray.length; i++){ //For each elememnt within the bookmark array.
JMenuItem menuItem = new JMenuItem(bookmarksArray[i]); //Create a new JMenuItem.
menuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){ //When clicked, go to the URL (that is also their name).
try {
URL tempUrl = new URL(menuItem.getText()); //Create new URL using their name.
toolBar.showPage(tempUrl, true); //showPage method from ToolBarMain class using new URL.
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, "Cannot fetch URL", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
bookmarkSubmenu.add(menuItem); //Add each menuItem to the bookmarkSubmenu.
}
return bookmarkSubmenu; //Return the bookmarkSubmenu to constructor.
}
private JMenuItem addBookmarks(){ //Method for creating a new bookmark.
String fileLocation = "Bookmarks.txt"; //File location of config file.
String newLine = System.getProperty("line.separator"); //Create new line property.
HomeWriter bookMarkWriter = new HomeWriter(fileLocation, true); //New instance of HomeWriter class, appends to file.
String[] bookmarksArray = getBookmarks(); //Get bookmark array.
URL currentUrl = editorPane.getPage(); //Get URL of current page.
JMenuItem menuItem = new JMenuItem(currentUrl.toString()); //Create new JMenuItem using currentURL as a name.
if(Arrays.asList(bookmarksArray).contains(currentUrl.toString())){ //Check for duplicates of currentURL in bookmark array.
JOptionPane.showMessageDialog(null, "Already a bookmark", "Error", JOptionPane.ERROR_MESSAGE); //If true, display error message using JOptionPane.
menuItem = null; //Set menuItem to null.
} else { //If no duplicates found then...
bookMarkWriter.writeToFile(currentUrl.toString() + newLine); //... Write to bookmark file.
}
return menuItem; //Return menuItem.
}
private void removeBookmark(){
String fileLocation = "Bookmarks.txt";
HomeWriter deleteBookmarks = new HomeWriter(fileLocation, false);
HomeWriter bookMarkWriter = new HomeWriter(fileLocation, true);
String[] bookmarksArray = getBookmarks();
URL currentUrl = editorPane.getPage();
String newLine = System.getProperty("line.separator");
for(int i = 0; i < bookmarksArray.length; i++){
if(bookmarksArray[i].equals(currentUrl.toString())){
bookmarksArray[i] = null;
}
}
deleteBookmarks.writeToFile("");
for(int i = 0; i < bookmarksArray.length; i++){
if(bookmarksArray[i] != null)
bookMarkWriter.writeToFile(bookmarksArray[i] + newLine);
}
}
}
http://www.ncl.ac.uk/computing/#
http://www.ncl.ac.uk/computing/research/
http://www.ncl.ac.uk/computing/people/
http://www.ncl.ac.uk/computing/research/
http://www.ncl.ac.uk/computing/#
http://www.ncl.ac.uk/computing/#
http://www.ncl.ac.uk/computing/#
http://www.ncl.ac.uk/computing/#
http://www.ncl.ac.uk/computing/current/
http://www.ncl.ac.uk/computing/#
http://www.ncl.ac.uk/computing/#
http://www.ncl.ac.uk/computing/#
http://www.ncl.ac.uk/computing/research/
http://www.ncl.ac.uk/computing/study/
http://www.ncl.ac.uk/computing/#
http://www.ncl.ac.uk/computing/study/
http://www.ncl.ac.uk/computing/#
http://www.ncl.ac.uk/computing/study/
http://www.ncl.ac.uk/computing/#
http://www.ncl.ac.uk/computing/contact/
http://www.ncl.ac.uk/computing/#
http://www.ncl.ac.uk/computing/current/
http://www.ncl.ac.uk/computing/contact/
http://www.ncl.ac.uk/computing/current/
http://www.ncl.ac.uk/computing/current/
/* Name: Will Wetzel - 130251255
* Program: Creating a Web browser - File reader.
* Module: CSC1022 - Programming II
* Description: This program will create a file reader constructor and methods for reading either a single line or a whole text file.
*/
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
public class HomeReader {
private String path;
HomeReader(String filePath) { //Constructor for file reader.
path = filePath;
}
String ReadLine() throws IOException { //Method for reading a single line.
FileReader reader = new FileReader(path); //File reader to read characters.
BufferedReader textReader = new BufferedReader(reader); //Buffered reader to read whole lines instead of single characters
String url; //String to store URL.
url = textReader.readLine(); //Read string and store.
textReader.close( ); //Close file.
return url; //Return URL.
}
StringBuilder ReadFile(){ //Method for reading a file.
try{
FileInputStream fileReader = new FileInputStream(path); //Create new file input stream using file path, to open file.
InputStreamReader inputStreamReader = new InputStreamReader(fileReader); //Create new input stream reader.
BufferedReader reader = new BufferedReader(inputStreamReader); //Use input stream reader to create new buffered reader.
StringBuilder buffer = new StringBuilder(); //Create string builder.
String line = null;
while ((line = reader.readLine()) != null) //While line reade does not equal null.
buffer.append(line + "<br>"); //Add to string builder.
reader.close(); //Close reader.
return buffer; //Retrn string builder.
} catch(IOException e){
JOptionPane.showMessageDialog(null, "Cannot read file", "Error", JOptionPane.ERROR_MESSAGE);
return null;
}
}
private int readLines() throws IOException{
FileReader reader = new FileReader(path); //File reader to read characters.
BufferedReader textReader = new BufferedReader(reader); //Buffered reader to read whole lines instead of single characters
String line;
int numberOfLines = 0;
while((line = textReader.readLine()) != null) //While there are strings in the document,
numberOfLines++; //Increment the numberOfLines variable.
textReader.close(); //Close file.
return numberOfLines; //Return integer of number of lines.
}
}
/* Name: Will Wetzel - 130251255
* Program: Creating a Web browser - File Writer.
* Module: CSC1022 - Programming II
* Description: This program contains two constructors, one for creating a file writer to append to a file and a constructor for deleting the contents
* of a file and rewriting it. It also contains the method for writing to a file.
*/
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JOptionPane;
public class HomeWriter {
private String path;
private boolean appendToFile; //False = File is rewritten.
public HomeWriter(String filePath) { //Constructor for just adding onto a file.
path = filePath;
}
public HomeWriter(String filePath , boolean appendValue) { //Constructor for rewriting file.
path = filePath;
appendToFile = appendValue;
}
public void writeToFile(String textLine){
FileWriter write;
try {
write = new FileWriter(path, appendToFile);
PrintWriter printLine = new PrintWriter(write); //PrintWriter to handle plain text.
printLine.print(textLine); //Write to file.
printLine.close(); //Close file.
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Cannot find file", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
/* Name: Will Wetzel - 130251255
* Program: Creating a Web browser - Tool bar set up (JPanel).
* Module: CSC1022 - Programming II
* Description: This program will create a JPanel constructor for the tool bar and will create all the JButtons and the JTextField for the URL's.
* This method also contains all the methods for the JButtons.
*/
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ToolBarMain extends JPanel{
private static final long serialVersionUID = 7732875208214525168L;
JEditorPane editorPane;
private JButton home, setHome, go, back, forward, reload; //Declaring buttons and tField here so methods after constructor...
JTextField tField; // ... can access them.
private List<URL> History = new ArrayList<URL>(); //ArrayList of browser history for back and forward buttons.
private int historyIndex;
public ToolBarMain(JEditorPane editorPane){
this.editorPane = editorPane;
// ***** Setting ToolBar layout. ***** //
setLayout(new FlowLayout());
// ****** Creating fields to add onto JPanel. ***** //
home = new JButton("Home");
setHome = new JButton("Set Home");
reload = new JButton("Reload");
tField = new JTextField(32);
go = new JButton("Go");
back = new JButton("Back");
forward = new JButton("Forward");
// ***** Adding action listeners for the fields on JPanel. ****** //
home.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
goHome(true);
}
});
setHome.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
URL currentUrl = editorPane.getPage(); //Find current URL
try {
setHome(currentUrl.toString());
} catch (IOException e) {
throw new RuntimeException(); //Cannot use JOptionPane here due to the actionPerformed
} // ... method so instead we throw a run time error.
}
});
reload.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event){
reload();
}
});
tField.addActionListener(new ActionListener(){ //Add actionListener to tField so when enter is pressed, it ...
public void actionPerformed(ActionEvent event){ // ... Calls the go method.
go();
}
});
go.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event){
go();
}
});
back.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
back();
}
});
forward.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
forward();
}
});
// ***** Adding fields onto JPanel. ***** //
add(back, BorderLayout.EAST);
add(forward, BorderLayout.EAST);
add(reload, BorderLayout.CENTER);
add(tField, BorderLayout.CENTER);
add(go, BorderLayout.CENTER);
add(home, BorderLayout.WEST);
add(setHome, BorderLayout.WEST);
setVisible(true);
}
// ***** End of Constructor and start of methods ***** //
void updateUrl(URL currentUrl){ //Displaying current page in tField.
tField.setText(currentUrl.toString()); //set the text in tField to the page URL.
}
private void reload(){ //Method for reload button.
URL verifiedUrl = verifyUrl(editorPane.getPage().toString()); //Get currentUrl string and verify.
showPage(verifiedUrl, false); //Display current URL. Do not add to history as it should already... // ... be there.
}
String goHome(boolean goPage){ //Method for getting home page URL and/or setting page to home.
String fileLocation = "HomePage.txt"; //File location of config file.
try{
HomeReader file = new HomeReader(fileLocation); //Creating new instance of file reader.
String url = file.ReadLine(); //Reading line from file.
if(goPage) //If true, call showPage method.
showPage(new URL(url), true);
return url;
} catch(IOException e){
JOptionPane.showMessageDialog(null, "Cannot return home page URL", "Error", JOptionPane.ERROR_MESSAGE);
return null;
}
}
void setHome(String url) throws IOException{ //Method for setting home page.
String fileLocation = "HomePage.txt"; //File location of config file.
HomeWriter file = new HomeWriter(fileLocation); //Create new instance of file writer.
file.writeToFile(url); //write URL to file.
}
private void go(){ //Method for go button.
URL verifiedUrl = verifyUrl(tField.getText()); //Calls method for checking URL in tField.
if (verifiedUrl != null) //If valid format, show the page in JEditorPane.
{
showPage(verifiedUrl, true);
} else { //Else display error message for an Invalid URL.
JOptionPane.showMessageDialog(null, "Invalid URL", "Error", JOptionPane.ERROR_MESSAGE);
}
}
private void back(){ //Method for back button.
historyIndex--; //Minus one from historyIndex.
if(historyIndex < 0) //If lower then zero.
historyIndex = 0; //Set to zero.
URL url = (URL) History.get(historyIndex); //Get Url index of History list.
showPage(url, false); //Show page, do not add to history.
}
private void forward(){ //Method for forward button.
historyIndex++; //Add one to the historyIndex.
if(historyIndex >= History.size()) //If index is larger than or equal to History size.
historyIndex = History.size() - 1; //Minus one from index (To avoid out of bounds error).
URL url = (URL) History.get(historyIndex); //New URL from index of History list.
showPage(url, false); //Show page, do not add to history.
}
private URL verifyUrl(String url){ //Method for verifying Url's in tField.
URL verifiedUrl = null;
if (!url.toLowerCase().startsWith("http://")){ //Checks it starts with http://
return null;
}
try{
verifiedUrl = new URL(url); //Create new URL using CorrectUrl.
} catch (Exception e){
JOptionPane.showMessageDialog(null, "Unable verify URL", "Error", JOptionPane.ERROR_MESSAGE);
return null;
}
return verifiedUrl; //Return URL.
}
void showPage(URL pageUrl, boolean addToHistory){ //Method for showing new page and adding it to History.
try{
editorPane.setPage(pageUrl); //Load and display newest page.
if(addToHistory) //If true, add page to History.
addToHistory(pageUrl);
updateUrl(pageUrl); //Update tField with new URL.
} catch (IOException e) { // Show error message if unable to load.
JOptionPane.showMessageDialog(null, "Unable to load page", "Error", JOptionPane.ERROR_MESSAGE);
}
}
void addToHistory(URL currentUrl) throws IOException{
String newLine = System.getProperty("line.separator"); //Initialize "newLine" to enter a newline when entered in a system.out statement.
historyIndex = History.size();
History.add(currentUrl); //Add URL to history.
String fileLocation = "History.txt"; //File location of config file.
HomeWriter historyFile = new HomeWriter(fileLocation, true); //Create new instance of file writer.
historyFile.writeToFile(currentUrl.toString() + newLine); //write URL to file.
}
void clearHistory(){ //Method for clearing History list.
History.clear();
}
}
/* Name: Will Wetzel - 130251255
* Program: Creating a Web browser - HyperLink Listener set up.
* Module: CSC1022 - Programming II
* Description: This program will creates the constructor for the HyperLink listener and creates the method to fetch and show a page from a hyper link.
*/
import java.net.URL;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.JEditorPane;
public class WebPaneActivatedHyperlinkListener implements HyperlinkListener
{
JEditorPane editorPane;
ToolBarMain toolBar;
public WebPaneActivatedHyperlinkListener(JEditorPane editorPane, ToolBarMain toolBar) { //Constructor for hyperlink listener.
this.editorPane = editorPane;
this.toolBar = toolBar;
}
@Override
public void hyperlinkUpdate(HyperlinkEvent hyperlinkEvent) {
HyperlinkEvent.EventType type = hyperlinkEvent.getEventType(); //Get type of event.
URL url = hyperlinkEvent.getURL(); //Fetch URL from hyper link.
if(type == HyperlinkEvent.EventType.ACTIVATED) { //If clicked on, show page and add to history.
toolBar.showPage(url, true);
}
}
}
/* Name: Will Wetzel - 130251255
* Program: Creating a Web browser - Set up.
* Module: CSC1022 - Programming II
* Description: This program will set up the basics for the web browser, such as the JFrame, JEditorPane and call constructors for the Hyperlink listener,
* JPanel and JMenu.
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.event.HyperlinkListener;
public class WebPaneMain
{
public WebPaneMain() throws IOException {
// ***** Create JFrame ***** //
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// ***** Create JEditorPane ***** //
JEditorPane editorPane = new JEditorPane();
editorPane.setEditable(false);
// ***** Create JPanel ***** //
ToolBarMain toolBar = new ToolBarMain(editorPane);
toolBar.goHome(true); //When created, set page of editorPane to the homepage.
// ***** HyperLink Lister set up here ***** //
HyperlinkListener hyperlinkListener = new WebPaneActivatedHyperlinkListener(editorPane, toolBar);
editorPane.addHyperlinkListener(hyperlinkListener);
// ***** JScrollPane set up here, adding it to frame. ***** //
JScrollPane scrollPane = new JScrollPane(editorPane);
frame.add(scrollPane);
frame.add(toolBar, BorderLayout.NORTH);
// ***** Creating a instance of fileMenu and adding to frame. ***** //
FileMenu fileMenu = new FileMenu();
frame.setJMenuBar(fileMenu.CreateFileMenu(editorPane, toolBar));
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); //Detect screen size.
frame.setSize(screenSize); //Use screen size as default frame size.
frame.setVisible(true);
}
public static void main(String[] args) throws IOException
{
WebPaneMain browser = new WebPaneMain();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment