// -------- File name mybrowser. Java, program number 18.4 --------------------
Import java. AWT. event .*;
Import javax. Swing .*;
Import javax. Swing. event .*;
Import java. AWT .*;
Import java.net .*;
Import java. Io .*;
Public class mybrowser implements actionlistener, hyperlinklistener {
// This class needs to implement the hyperlinklistener interface to respond to user points
// Click the hyperlink event
Jlabel msglbl;
Jtextfield urltext; // enter the URL for the user
Jeditorpane content; // display webpage content
Jscrollpane jspanel;
Jpanel;
Container con;
Jframe mainjframe;
// Constructor for the layout of the Program Interface
Public mybrowser (){
Mainjframe = new jframe ("My Browser ");
Mainjframe. setdefaclocloseoperation (jframe. exit_on_close );
Con = mainjframe. getcontentpane ();
Msglbl = new jlabel ("input address :");
Urltext = new jtextfield ();
Urltext. setcolumns (20 );
Urltext. addactionlistener (this );
Panel = new jpanel ();
Panel. setlayout (New flowlayout ());
Panel. Add (msglbl );
Panel. Add (urltext );
Content = new jeditorpane ();
Content. seteditable (false );
// Add a hyperlink event listener for content
Content. addhyperlinklistener (this );
Jspanel = new jscrollpane (content );
Con. Add (panel, borderlayout. North );
Con. Add (jspanel, borderlayout. center );
Mainjframe. setsize (800,600 );
Mainjframe. setvisible (true );
Mainjframe. setdefaclocloseoperation (jframe. exit_on_close );
}
// Call this method when the user presses the Enter key
Public void actionreceivmed (actionevent e ){
Try {
// Construct a URL object based on user input
URL url = new URL (urltext. gettext ());
// Obtain and display the webpage content
Content. setpage (URL );
} Catch (malformedurlexception El ){
System. Out. println (E. tostring ());
} Catch (ioexception El ){
Joptionpane. showmessagedialog (mainjframe, "connection error ");
}
}
// Implement the hyperlinkupdate method. When a user clicks a link on a webpage, the system calls this method.
Public void hyperlinkupdate (hyperlinkevent e ){
If (E. geteventtype () = hyperlinkevent. eventtype. Activated ){
Try {
URL url = E. geturl (); // obtain the URL clicked by the user
Content. setpage (URL); // jump to the new page
Urltext. settext (E. geturl (). tostring (); // update the URL in the user input box.
} Catch (malformedurlexception El ){
System. Out. println (E. tostring ());
} Catch (ioexception El ){
Joptionpane. showmessagedialog (mainjframe, "connection error ");
}
}
}
Public static void main (string [] ARGs ){
New mybrowser ();
}
}