Java Help Files. by Peter Lavin. May 22, 2004

Similar documents
Swing from A to Z Some Simple Components. Preface

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Class 16: The Swing Event Model

AP CS Unit 11: Graphics and Events

Introduction This assignment will ask that you write a simple graphical user interface (GUI).

Chapter 13 Lab Advanced GUI Applications

RAIK 183H Examination 2 Solution. November 11, 2013

Chapter 13 Lab Advanced GUI Applications Lab Objectives. Introduction. Task #1 Creating a Menu with Submenus

RAIK 183H Examination 2 Solution. November 10, 2014

Window Interfaces Using Swing Objects

Swing from A to Z Using Focus in Swing, Part 2. Preface

MIT AITI Swing Event Model Lecture 17

First Name: AITI 2004: Exam 2 July 19, 2004

Java - Applications. The following code sets up an application with a drop down menu, as yet the menu does not do anything.

Object-Oriented Programming: Revision. Revision / Graphics / Subversion. Ewan Klein. Inf1 :: 2008/09

First Name: AITI 2004: Exam 2 July 19, 2004

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

Window Interfaces Using Swing Objects

Systems Programming Graphical User Interfaces

Packages: Putting Classes Together

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

H212 Introduction to Software Systems Honors

CS Exam 1 Review Suggestions

Part 3: Graphical User Interface (GUI) & Java Applets

Introduction to the JAVA UI classes Advanced HCI IAT351

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

Lecture 5: Java Graphics

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) )

GUI Forms and Events, Part II

Name: Checked: Learn about listeners, events, and simple animation for interactive graphical user interfaces.

Graphics User Defined Forms, Part I

Queen s University Faculty of Arts and Science School of Computing CISC 124 Final Examination December 2004 Instructor: M. Lamb

JRadioButton account_type_radio_button2 = new JRadioButton("Current"); ButtonGroup account_type_button_group = new ButtonGroup();

CMSC 150 Lab 8, Part II: Little PhotoShop of Horrors, Part Deux 10 Nov 2015

CSIS 10A Assignment 7 SOLUTIONS

Lecture 3: Java Graphics & Events

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

Graphical User Interface (Part-1) Supplementary Material for CPSC 233

Improved Web Development using HTML-Kit

SE1021 Exam 2. When returning your exam, place your note-sheet on top. Page 1: This cover. Page 2 (Multiple choice): 10pts

CS180 Spring 2010 Exam 2 Solutions, 29 March, 2010 Prof. Chris Clifton

Programming Language Concepts: Lecture 8

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University

1.00/1.001 Introduction to Computers and Engineering Problem Solving Fall (total 7 pages)

Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics

Chapter 12 Advanced GUIs and Graphics

University of Cape Town ~ Department of Computer Science. Computer Science 1016S / 1011H ~ January Exam

Starting Out with Java: From Control Structures Through Objects Sixth Edition

CS 11 java track: lecture 3

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

Midterm assessment - MAKEUP Fall 2010

Chapter 13. Applets and HTML. HTML Applets. Chapter 13 Java: an Introduction to Computer Science & Programming - Walter Savitch 1

Name: CSC143 Exam 1 1 CSC 143. Exam 1. Write also your name in the appropriate box of the scantron

An Exceptional Class. by Peter Lavin. June 1, 2004

Swing - JButton. Adding buttons to the main window

encompass a group of features for building Graphical User Interfaces (GUI).

Introduction. Introduction

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

PART1: Choose the correct answer and write it on the answer sheet:

Final Exam CS 251, Intermediate Programming December 13, 2017

Parts of a Contract. Contract Example. Interface as a Contract. Wednesday, January 30, 13. Postcondition. Preconditions.

Chapter 1 GUI Applications

User interfaces and Swing

Using HTML Kit to Debug Server-Side Scripts

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction

Graphical User Interface (GUI)

SINGLE EVENT HANDLING

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

1005ICT Object Oriented Programming Lecture Notes

Points Missed on Page page 1 of 8

Dr. Hikmat A. M. AbdelJaber

Building Graphical User Interfaces. GUI Principles

Chapter Two Bonus Lesson: JavaDoc

ITEC 120 4/14/11. Review. Need. Objectives. GUI basics JFrame JPanel JLabel, JButton, JTextField Layout managers. Lecture 38 GUI Interactivity

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

1.00 Lecture 14. Lecture Preview

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1

CS Exam 3 - Spring 2010

Graphical User Interface (GUI)

Graphical User Interface

+! Today. Lecture 3: ArrayList & Standard Java Graphics 1/26/14! n Reading. n Objectives. n Reminders. n Standard Java Graphics (on course webpage)

Example: Building a Java GUI

CSCI 201L Written Exam #1 - SOLUTION Fall % of course grade

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

Java. GUI building with the AWT

Example: Building a Java GUI

Graphical interfaces & event-driven programming

1.00/1.001 Introduction to Computers and Engineering Problem Solving Spring Quiz 2

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN

Calculator Class. /** * Create a new calculator and show it. */ public Calculator() { engine = new CalcEngine(); gui = new UserInterface(engine); }

Graphical User Interfaces (GUIs)

Example: CharCheck. That s It??! What do you imagine happens after main() finishes?

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Transcription:

Java Help Files by Peter Lavin May 22, 2004

Overview Help screens are a necessity for making any application user-friendly. This article will show how the JEditorPane and JFrame classes, along with HTML files, can be used to create help windows for any Java application. This is a projectoriented article that will walk the reader through all the code needed for development. Some familiarity with Java is assumed. Java Help Files Page 1

Introduction HTML files are often used to display help for desktop applications. For example, the help files that accompany many Windows applications are usually made up of compiled HTML files. Using HTML with Java is relatively easy because Java has built-in HTML capabilities. You can control the way text appears in components by using HTML coding. For example, if you want to bold the text of a JButton the following code will do this for you: JButton mybutton = new JButton(); mybuttom.settext( <html><b>press Me</b></html> ); Given that Java has this innate capability it is not difficult to develop a class that will display help files in HTML format. In this article we will take you through the steps necessary to create such a class and, because the actual help files will be independent of the application, you will be able to use this class with any Java application. Before looking at the code let s clearly state what we want our class to do. It will provide help information for any application by browsing local HTML files. To keep things simple we will navigate using a home page that is a list of hyperlinks to specific help files. Pages may exceed the size of the screen so our application will need to be able to scroll. The Code Find below a complete listing of the code in our class. Have a quick look at it now but don t worry if you don t understand all the details. Some basic knowledge of Java is assumed so not all the lines of code will be discussed. Relevant sections will be explained in detail. 1:////////////////////////////////////////////////////////////////// 2:/** 3:* This class creates a frame with a JEditorPane for loading HTML 4:* help files 5:*/ 6://package goes here 7:import java.io.*; 8:import javax.swing.event.*; 9:import javax.swing.*; 10:import java.net.*; 11:import java.awt.event.*; 12:import java.awt.*; 13: 14:public class HelpWindow extends JFrame implements ActionListener{ Java Help Files Page 2

15: private final int WIDTH = 600; 16: private final int HEIGHT = 400; 17: private JEditorPane editorpane; 18: private URL helpurl; 19:////////////////////////////////////////////////////////////////// 20:/** 21: * HelpWindow constructor 22: * @param String and URL 23: */ 24:public HelpWindow(String title, URL hlpurl) { 25: super(title); 26: helpurl = hlpurl; 27: editorpane = new JEditorPane(); 28: editorpane.seteditable(false); 29: try { 30: editorpane.setpage(helpurl); 31: } catch (Exception ex) { 32: ex.printstacktrace(); 33: } 34: //anonymous inner listener 35: editorpane.addhyperlinklistener(new HyperlinkListener() { 36: public void hyperlinkupdate(hyperlinkevent ev) { 37: try { 38: if (ev.geteventtype() == HyperlinkEvent.EventType.ACTIVATED) { 39: editorpane.setpage(ev.geturl()); 40: } 41: } catch (IOException ex) { 42: //put message in window 43: ex.printstacktrace(); 44: } 45: } 46: }); 47: getcontentpane().add(new JScrollPane(editorpane)); 48: addbuttons(); 49: // no need for listener just dispose 50: setdefaultcloseoperation(dispose_on_close); 51: // dynamically set location 52: calculatelocation(); 53: setvisible(true); 54: // end constructor 55:} 56:/** 57: * An Actionlistener so must implement this method 58: * 59: */ 60:public void actionperformed(actionevent e) { 61: String straction = e.getactioncommand(); 62: URL tempurl; 63: try { 64: if (straction == "Contents") { 65: tempurl = editorpane.getpage(); 66: editorpane.setpage(helpurl); 67: } 68: if (straction == "Close") { Java Help Files Page 3

69: // more portable if delegated 70: processwindowevent(new WindowEvent(this, 71: WindowEvent.WINDOW_CLOSING)); 72: } 73: } catch (IOException ex) { 74: ex.printstacktrace(); 75: } 76:} 77:/** 78: * add buttons at the south 79: */ 80:private void addbuttons() { 81: JButton btncontents = new JButton("Contents"); 82: btncontents.addactionlistener(this); 83: JButton btnclose = new JButton("Close"); 84: btnclose.addactionlistener(this); 85: //put into JPanel 86: JPanel panebuttons = new JPanel(); 87: panebuttons.add(btncontents); 88: panebuttons.add(btnclose); 89: //add panel south 90: getcontentpane().add(panebuttons, BorderLayout.SOUTH); 91:} 92:/** 93: * locate in middle of screen 94: */ 95:private void calculatelocation() { 96: Dimension screendim = Toolkit.getDefaultToolkit().getScreenSize(); 97: setsize(new Dimension(WIDTH, HEIGHT)); 98: int locationx = (screendim.width - WIDTH) / 2; 99: int locationy = (screendim.height - HEIGHT) / 2; 100: setlocation(locationx, locationy); 101:} 102:public static void main(string [] args){ 103: URL index = ClassLoader.getSystemResource("index.html"); 104: new HelpWindow("Test", index); 105: 106:} 107:}//end HelpWindow class 108://////////////////////////////////////////////////////////////// The HelpWindow Class The first thing to notice about our class is that it extends JFrame (line 14). We need not have done things this way. We could simply have included an instance of the JFrame class as a data member. However, we want our class to have all the functionality of the JFrame class. By using inheritance we will be able to directly change the title or the size of our frame by using the parent methods, settitle and setsize. After all, this is the whole point of object-oriented languages. Java Help Files Page 4

ActionListener Our class will also implement the interface ActionListener (line 14) so that it can easily react to events, principally mouse clicks. This is the most commonly used listener and requires that we implement the actionperformed method. Lines 60 through 76 implement this method and process button clicks. This method will be dealt with in detail shortly. Data Members & Constructor Only four data members are included in our class (Lines 15 through 18). Two are simple integers used to set the size of the frame. These variables are declared as final and will be used as default values. Using variables instead of literals makes for easier code maintenance and declaring them final means that they cannot be changed. The two remaining data members are URL and JEditorPane objects respectively. An URL is fairly self-explanatory, it is constructed from an HTML page in the same directory as our application, but the JEditorPane is a bit more interesting. However, before moving on to a discussion of JEditorPane a few comments about the constructor (lines 24-55). are in order. The constructor accepts two arguments, a title for the application and a home page for our help files. The first line of the constructor code (line 25) is a call to the parent constructor in order to set the title of our application. The home page should be a list of hyperlinks to specific help files, although for testing purposes any HTML page will do. This URL is assigned to a class variable. JEditorPane Class This is the class that will be our help file browser. It can handle content formatted as text, rich text or HTML. We don t have to do anything special to enable it to handle HTML files. As the Sun online tutorial says, It effectively morphs into the proper kind of text editor for the kind of content it is given. This happens on line 30 where the content is set to an URL. One important thing that we do need to do with this component is add a HyperTextListener. Lines 35 46 create an anonymous inner listener of this class so that information is updated if a hyperlink is clicked. This listener simply Java Help Files Page 5

calls the setpage method to change URLs. If you need more information about listeners see the article Listeners In Java also found on this website. The JEditorPane class is a component that gets added to our main, JFramederived class. This happens on line 47. Because our parent class is a JFrame it comes with a BorderLayout as its default layout manager. When an item is added to a JFrame s contentpane its default location will be at the centre of the JFrame and this is exactly what we want. The actionperformed Method Buttons are added to our application in the addbuttons method (starting on line 80), and the application itself is added as an ActionListener to both buttons. All this means is that our buttons are able to react to events. The code that processes events is the actionperformed method (line 60 and following). Our Contents button functions as a Home Page button by returning to the list of hyperlinks to specific help files. The Close button simply disposes of our help window but perhaps a few comments are in order. The line: processwindowevent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));, could just as easily have been replaced with, dispose(); However, creating a window closing event makes for more robust code. If we decide to add a window listener that handles the window closing event then we will ensure that the same code will execute regardless of whether the user shuts down the application from the title bar or by pressing the Close button. In other words we will handle the closing event in one location only. It is also worth noting that our help window is disposed of when it is closed. This behaviour is set on line 50. It is important that the default close operation not be set to EXIT_ON_CLOSE because the class described here is an ancillary class and closing it should not end the application. Also, with this in mind, don t forget to remove the main method before you incorporate this class into another class. The main method is included here simply for testing purposes. Enhancements Java Help Files Page 6

The class we ve created is a very basic use of JEditorPane to display HTML help files. There are numerous ways in which it could be improved and I will make a few suggestions here. Buttons to navigate to previously visited URLs might be helpful. A menubar might provide a more elegant means of navigation. Remember also that this class retains all the functionality of its parent. If you are not satisfied with the size of the window you can simply use the setsize method inherited from the JFrame class. Likewise with methods such as setbackground. Furthermore, the functionality of this class could be extended by deriving other classes from it. That said, it is best to remember that Java only supports HTML version 3.2 and this fact will certainly restrict what can be achieved. Finally, the way in which exceptions are handled could be improved. In a followup article we will show how to construct a generic class to handle exceptions thrown by any application. To summarise, we have presented a class that creates a basic help window and can be incorporated into any Java application. In so doing we have achieved one of the goals of object-oriented programming namely creating a reusable class. About the Author Peter Lavin runs a Web Design/Development firm in Toronto, Canada. For more information visit http://www.softcoded.com. He may be reached at peterlavin@sympatico.ca. Java Help Files Page 7