© its, inc. [email protected] java graphics learn java applet and user interface awt swing

40
© ITS, Inc. Jeff[email protected] Java Graphics Learn Java Applet and User Interface AWT Swing

Upload: marilyn-robinson

Post on 26-Dec-2015

219 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

Java Graphics

Learn Java Applet and User Interface

AWT

Swing

Page 2: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

Creating a Java Applet.

Java Applet is a different (from application) type of a program. Java Applet is a part of a web page, pretty much like an image on this page. A web browser is the main program that reads web page, renders images, and also can use its Java library to play Java Applet code.

This is why Java Applet does not have the main() method. The browser starts applet with the init() method. In the example below a very simple Java Applet paints its part of a web page with an image and several lines of Java Poetry.

The paint() method is also called by the browser automatically whenever there is a need to refresh the screen. You can see that all programmer needs to do for this simple applet is to fill the init() and paint() methods with several lines of code.

Page 3: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

Applet Skills

 URL getDocumentBase() - Gets the URL of the document in which this applet is embedded. 

Image getImage(URL url) - Returns an Image object that can then be painted on the screen. 

String getParameter(String name) - Returns the value of the named parameter in the HTML tag. 

void init() - Called by the browser or applet viewer to inform this applet that it has been loaded into the system. 

void play(URL url) - Plays the audio clip at the specified URL

void start() - Called by the browser or applet viewer after init()

void stop() - Called by the browser or applet viewer to inform this applet that it should stop its execution. 

Page 4: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

Applet and AppletContext

Applet can get access to browser’s resources

 AppletContext getAppletContext() - Determines this applet's context, which allows the applet to query and affect the environment in which it runs.

AppletContext

Enumeration getApplets() - Finds all the applets in the document represented by this applet context. 

AudioClip getAudioClip(URL url) - Creates an audio clip.

void showDocument(URL url) - Replaces the Web page currently being viewed with the given URL. 

void showStatus(String status) - Requests that the argument string be displayed in the "status window".

Page 5: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

Applet Example

Page 6: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

AppletExample.class at Work

The Java applet uses its network capabilities to load an image from the network and draws this image along with several lines of Java poetry.

A web browser invokes the init() method as soon as the applet is loaded.

Then the browser will refresh the screen by calling the paint() method of the applet. More precisely the browser will call the invisible update() method that in its turn will schedule execution of the paint() method. This is the mechanics of painting Java components.

An applet or an application can draw different items on the java.awt.Component using the paint(Graphics) method.

Images, lines, circles, polygons or any other graphical items are drawn on a Graphics instance. The system (In the applet case it is the browser) passes the graphics instance to the paint(Graphics) method.

Page 7: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

The paint(Graphics) methodThe paint method might be called multiple times throughout the life of an applet or an application. The system allocates a thread and gives to this thread a specific time to accomplish its painting job.

If the drawing is heavy this time is not necessary enough and the paint() method can be called several times for a single screen refresh that can often cause a flickering effect.

When the system calls the paint() method?If an applet changes location on the screen or any time it needs to be refreshed (redrawn), paint(Graphics) is called. Programmers do not directly call paint(Graphics).

To have java.awt.Component paint itself programmers call repaint(); repaint() will call update(Graphics) that in its turn calls paint(Graphics).

Be aware that update(Graphics) assumes that the component background is not cleared and clears background first. If you don't want to waste time to clear the background each time you want to paint, it's a good idea to override the update(Graphics) method.

Page 8: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

Applet Deployment

It is relatively easy to deploy the applet. You can place the compiled AppletExample.class file on the web server in the same folder where you have your web page.

You can also put the web page as well as your applet class on your local machine for testing. Your web page must have the applet tag, in a very similar way as you would do this for an image.

<applet code="AppletExample.class" width=200 height=300> </applet>

Save html file with the applet tag as MyApplet.html

Java Applet will be loaded and running in the web browser as soon as a user will point the browser to your web page. Try to modify this code and create another applet.

Page 9: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

Applet Parameters

Applet tag can include parameters.

<html>

<!– some html code -->

<applet code=“ArtApplet.class" width=600 height=400>

<param name=“image1” value=“jar.gif”>

<param name=“image2” value=“itsLogo.gif”>

</applet> <!-- more html … -->

Java Applet program, like the ArtApplet, can pick up these parameters with the getParameter() method.

String imageName = getParameter(“image1”);

Page 10: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

The ArtApplet Uses Parametersimport java.applet.Applet;import java.awt.*;import java.util.ArrayList;/** * The ArtApplet draws a gallery of images * with their names */public class ArtApplet extends Applet { // we'll use applet parameters to pass gallery of images private ArrayList images = new ArrayList(); private ArrayList imageNames = new ArrayList(); // parameters names are “image1”, “image2”, etc… public void init() { for(int i=0; true; i++) { String paramName = "image" + (i+1); String imageName = getParameter(paramName); if(imageName == null) { break; // end of images - end of the loop } Image image = getImage(getCodeBase(),imageName); images.add(image); imageNames.add(imageName); } }

Page 11: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

The ArtApplet Draws a Gallery

/** * The paint() method uses the for-loop * to draw each image with its name below * Images are collected in the ArrayList images * Image names are collected in the ArrayList imageNames * @param g */ public void paint(Graphics g) { g.setFont(new Font("Helvetica", Font.BOLD, 12) ); // text font int y = 40; // initial Y coordinate; the Y will increase in the loop for(int i = 0; i < images.size(); i++) { Image image = (Image) images.get(i); String imageName = (String)imageNames.get(i); if(image != null) { g.drawImage(image, 10, y, this); y += image.getHeight(this) + 12; // adjust Y for image size g.drawString(imageName, 10, y); } } }}

Page 12: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

Programming GUI in JavaAWTThe Java GUI is based on the Abstract Window Toolkit (java.awt) package that provides basic graphic abstractions and primitives.

SwingThe java.awt package makes a unified GUI for all platforms and serves as a base for rich graphic components built with the set of Swing (javax.swing) packages, also called Java Foundation Classes (JFC). Most of Java programmers use Swing to create rich graphics applications.

SWTAn alternative GUI is provided in Java with the Standard Widget Toolkit (SWT). SWT uses a Java native interface (JNI) to C to invoke the native operating system graphics widgets from Java code. SWT enforces one-to-one mapping between Java native methods and operating system calls, which makes a very significant difference in the appearance and performance of graphics.

SWT is a pure Java code (although not from Sun Microsystems) widely accepted by the Java development community and supported by IBM and other organizations under the eclipse.org umbrella.

Page 13: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

The AWT package. Abstract Windowing Toolkit. java.awt.*

Graphics abstractions, Components, and Layout Managers

Graphics abstractions are defined by colors, fonts, images, etc.java.awt.Color, java.awt.Font, java.awt.Image

Components, like buttons, panels, lists, checkboxes, and other widgets are defined with their attributes.

Layout Managers are the objects that are used to control the layout of components.

Three most commonly used Layout Managers are: - the FlowLayout, - the BorderLayout, and - the GridLayout.

Page 14: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

Commonly used Layout Managers

Java Applet serves two roles: as a networking service and as a graphical component.

The Java Applet class graphically represents java.awt.Panel.

The default layout for the Panel is the FlowLayout.The FlowLayout is the default layout manager for the simplest Java Container, the Panel class.

The FlowLayout with Center justification is used by default. There are FlowLayout.CENTER, FlowLayout.LEFT and FlowLayout.RIGHT justifications.

Page 15: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

The BorderLayout

The BorderLayout (default for the Frame and the Dialog classes) has 5 regions: North, South, East, West and Center. When a user resizes the window with the BorderLayout the North and South regions grow horizontally while the East and West Regions grow vertically. The Center region grows in both directions. It is not a requirement to fill all 5 fields of the BorderLayout (see example).

Page 16: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

The GridLayoutThe buttons are placed into the frame with the GridLayout. The number of regions for a GridLayout is specified in the constructor by rows and columns. In this case we specified 3 rows with two columns for the layout.

The GridLayout makes all regions the same size, equals to the largest cell.Creating a frame makes this applet less dependable on the web browser. The frame will stay on the screen while a user can continue browsing different pages.

The Tickets class (see the next slide) definition includes the promise to implement the ActionListener interface. This simply means that ActionEvent handling happens in this class and this class must provide the actionPerformed() method implementation.When any of destination buttons is pressed a button label is changed to show a corresponding fixed price.

Page 17: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

GridLayout Code Example

// Tickets (in the GridLayout)import java.applet.Applet;import java.awt.*;import java.awt.event.*;

/** * The Tickets applet demonstrates Grid Layout and event handling */public class Tickets extends Applet implements ActionListener { private String[] price = { "$100","$200","$250","$500","$750","$990"}; private String[] city = { "Phoenix", "Chicago", "Los Angeles", "New York", "London", "Moskow"}; private Button[] buttons;

This example greatly simplifies backend operations required for such search. The code focuses on the graphics and event handling instead.

Page 18: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

GridLayout Code Example (2)

/** * The init() method will be called by browser as soon as applet loaded */ public void init() { Frame f = new Frame("Best air fair from Denver"); f.setLayout(new GridLayout(3, 2, 2,2)); buttons = new Button[city.length]; for (int i = 0; i < city.length; i++) { buttons[i] = new Button(city[i]); f.add (buttons[i]); // delegate event handling to THIS object buttons[i].addActionListener(this); } f.setSize(400,300); f.setVisible(true); }

Page 19: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

GridLayout Code Example (3)

/** * The actionPerformed() method is the event handler * It sets the price label for a selected city */ public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); for(int i=0; i < city.length; i++) { if(city[i].equals(command) ) { buttons[i].setLabel(price[i]); } else { buttons[i].setLabel(city[i]); } } }}

Page 20: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

Handling Events in JavaListeners and the Observer Design Pattern

Delegation Model allows you to separate GUI from event processing.

A specific listener object has to be added to each component that expect events.

Listeners are interfaces. They must be implemented in your code.

For example, each ActionListener object must implement the method actionPerformed() reacting to the button press. Note that every button has its own ActionListener ...

MouseListener object has to be added to implement specific methods of reacting to mouse click: mouseClicked(), mousePressed(), mouseReleased(), mouseEntered(), mouseExited() ...

KeyListener object has to be added to implement specific methods reacting to the keyboard press: keyPressed(), keyReleased(), keyTyped()

ActionListener object can be added to a button or menu item and must implement the actionPerformed() method

Page 21: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

From hard-coded GUI to a flexible Scenario // WebContainerimport java.applet.Applet;

/** * WebContainer is an applet * The init() method provides access to XML-based application scenario * @author [email protected] */public class WebContainer extends Applet { /** * init() method is called by a web browser when applet just started * The method uses applet.getParameter() method to read urlToScenario * */ public void init() { String urlToScenario = getParameter("scenario"); // Applet can only access URL to its own server host String scenario = JavaIOExample.fetchURL(urlToScenario ); ServiceFrame frame = new ServiceFrame(scenario); }}

Page 22: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

JBuilder Supports Applets

Page 23: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

Exploring Applets with JBuilder Applets and Swing components

Most browsers do not support Swing components and other new JDK features. For best results, write your applet using the same JDK that the browser uses and use AWT components instead of Swing.

Use Sun's Java Plug-in for applets if you're writing your applets with the newer JDKs: http://java.sun.com/products/plugin/

Different ways to run your applet

Right-click the applet HTML file in the project pane to run your applet in Sun's appletviewer.

Choose Run|Run Project to run your applet in JBuilder's applet viewer, AppletTestbed.

Quickly create applets with the Applet wizard. Choose File|New|Web, and double-click the Applet icon.

Debug applets from Internet Explorer or Netscape Navigator using the Java Plug-in and JBuilder's debugger.

Reference: JBuilder X "Working with applets"

Page 24: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

Applet Wizard

How to start:

File - New - Web - Applet icon to open the Applet wizard.Do not change the suggested package name. Type a new name for the applet class.Select the base class: java.applet.Applet or java.swing.JApplet.

Options: Generate Header Comments - Uses information from the project file as header comments at the top of the applet class file. Can Run Standalone - Creates a main() method so you can test the applet without its being called from an HTML page. Generate Standard MethodsCreates stubs for the standard applet methods: init(), start(), stop(), destroy(), getAppletInfo(), and getParameterInfo().

Use JBuilder Tutorial: Building an applet

Page 25: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

Use JBuilder Help to Navigate

Page 26: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

Summary

• Java Applet• AWT basics• Handling Events• JBuilder Supports Applets• From Hard-Coded to Flexible Interface

Page 27: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

Swing or JFC

Page 28: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

SwingExampleimport java.awt.*; import java.awt.event.*; import com.sun.java.swing.*; import com.sun.java.accessibility.*; /** * The SwingExample class shows an example of Swing-based GUI */public class SwingExample implements ActionListener { private JFrame jFrame; private JLabel jLabel; private JPanel jPanel; private JButton jButton; private AccessibleContext accContext; private String labelPrefix = "Number of button clicks: "; private int numClicks = 0;

// The actionPerformed() method handles the button press public void actionPerformed(ActionEvent e) { numClicks++; jLabel.setText(labelPrefix + numClicks); }

Page 29: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

SwingExample (2)

// The go() method builds the GUIpublic void go() { // Here is how you can set up “lookAndFeel” try { UIManager.setLookAndFeel( UIManager.getLookAndFeel()); } catch (UnsupportedLookAndFeelException e) { System.err.println("Couldn't use the default look and feel " + e); } jFrame = new JFrame("HelloSwing"); jLabel = new JLabel(labelPrefix + "0"); jButton = new JButton("I am a Swing button!"); // Create a shortcut: make ALT-i be equivalent // to pressing mouse over button. jButton.setMnemonic('i'); jButton.addActionListener(this); // Add support for accessibility. accContext = jButton.getAccessibleContext(); accContext.setAccessibleDescription("Pressing this button increments the number of button clicks");

Page 30: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

SwingExample (3) jPanel = new JPanel(); jPanel.setBorder( BorderFactory.createEmptyBorder(30,30,10,30)); jPanel.setLayout(new GridLayout(2, 1)); // all components in one column // Put compts in pane, not in JFrame directly. jPanel.add(jButton); jPanel.add(jLabel); jFrame.setContentPane(jPanel); // set the Pane as a component holder // Set up a WindowListener inner class to handle window's quit button. WindowListener wl = new WindowAdapter() { // anonymous public void windowClosing(WindowEvent e) { // inner class System.exit(0); } // end of the windowClosing() method that handles this event }; // end of anonymous inner class created on-the-fly jFrame.addWindowListener(wl); jFrame.pack(); jFrame.setVisible(true); } // end of go() method public static void main(String[] args) { // The main() method is for testing SwingExample example = new SwingExample(); example.go(); } // end of the main() method} // end of the SwingExample class

Page 31: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

Swing Basic Steps and HintsGeneral Hints: Import Swing packages • Choosing the look and feel

– getLookAndFeel() • Setting up a Window container

– JFrame is similar to Frame – You cannot add components directly to JFrame – A content pane contains all of the Frame's visible components

except menu bar Hints of Building a Swing GUI • Start with top-level containers (JFrame, JApplet, JDialog, and

JWindow) • Create lightweight components (such as JButton, JPanel, and

JMenu) • Add lightweight components to a content pane associated with a top-

level container Swing components are subclasses of the JComponent Class that

provide:• Borders • Double buffering • Tool tips • Keyboard navigation • Application-wide pluggable look and feel

Page 32: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

Java GUI with Swing Classes: The ServiceBrowser Example

Java Swing classes offer a big set of rich graphical widgets with very powerful functionality. I provide only one example to demonstrate some of these features.

The JEditorPane class is the focus of the following example. The JEditorPane is a Web browser emulator. Yes! This single class is as capable of loading and showing Web pages as almost any real browser. The JEditorPane does not perform JavaScript functions, and it is very picky about HTML code correctness, unlike most browsers, which forgive Web designers for small errors.

The JEditorPane class can also display documents with rich text format (RTF) prepared by Microsoft Word, Open Office, or Adobe tools.

The next page code example loads the Web page with images, text, and hyperlinks that look like regular HTML links. Some of these links are not usual. A regular Web browser cannot interpret them, but our code will exceed the browser’s capacities. We write the link handler method, and we can greatly extend the browser’s functionality.

Page 33: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

ServiceBrowser with JEditorPane// ServiceBrowser

package.com.its.connector;

import javax.swing.*;import javax.swing.event.*;import javax.swing.text.html.*;

/** * ServiceBrowser class is an example from the book * "Integration-Ready Architecture and Design" * [email protected] */public class ServiceBrowser extends JFrame implements HyperlinkListener { public static boolean debug = true; protected JEditorPane display = new JEditorPane(); // main browser frame protected JScrollPane displayPane = new JScrollPane(display); // scrollable protected JEditorPane controls = new JEditorPane(); // browser controls /** * The constructor sets the initial urls and creates several HTML frames * Each HTML frame is represented by the JEditorPane */

Page 34: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

ServiceBrowser with JEditorPane (2) public ServiceBrowser(String initialURL, String controlsURL, String imageURL) { // set display pane (main frame) display.setEditable(false); // first browsing not editing, can change it later on display.setContentType("text/html"); // can change it later on

// set controls pane (top frame) controls.setEditable(false); // can change it later on controls.setContentType("text/html"); // can change it later on

// contentPane is the main holder for JFrame components Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); // place frames in the content pane contentPane.add(BorderLayout.CENTER, displayPane); contentPane.add(BorderLayout.NORTH, controls);

// set size of the window as 5/6 of the screen int w = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(); int h = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight(); w = (int)(w*5)/6; h = (int)(h*5)/6; // set size of the main and control frames displayPane.setPreferredSize(new Dimension(w-8, h-150)); controls.setSize((new Dimension(w-8, h-100));

Page 35: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

ServiceBrowser with JEditorPane (3) // get the logo image Image image = Toolkit.getDefaultToolkit().getImage(imageURL); setIconImage(image); // place icon on the frame setTitle(initialURL); // set initial url on the frame title

// enable hyperllink handler display.addHyperlinkListener(this); // load the initial web page and control page display.setPage(initialURL); controls.setPage(controlsURL);

frame.pack(); frame.setVisible(true); } /** * The hyperlinkUpdate() method handles HTML events * @param e */ public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { if (e instanceof HTMLFrameHyperlinkEvent) { // just an event notification HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent)e; // retrieve a document (web page) HTMLDocument doc = (HTMLDocument)display.getDocument(); doc.processHTMLFrameHyperlinkEvent(evt); } else { // click on the link

Page 36: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

ServiceBrowser with JEditorPane (4) // handling a click on the link try { String url = e.getURL().toString(); setTitle(url); // check if this your custm service instruction if(url.startsWith("service://”)) { // provide your own custom service that is not a part of any browser return; } else if(docOrURL.startsWith("http://") || docOrURL.startsWith("file://") { url = documentOrURL; // will open a page with the URL } else { // plain text display.setContentType("text/plain"); // can change it later on display.setText(docOrURL); return; } } // Load and display a web page in the JEditorPane display.setPage(url); // the display is the JEditorPane component } catch (Throwable t) { t.printStackTrace(); } } } }

Page 37: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

ServiceBrowser at Work

The ServiceBrowser class is an example of the javax.swing.JEditorPane in action. Like the java.awt.Frame, the javax.swing.JFrame is the main window in Swing GUI.

The ServiceBrowser class extends the JFrame and implements the javax.swing.event.HyperlinkListener. This means that the class must include the hyperlinkUpdate() method to handle link events.

Two GUI components cover all our needs: the JEditorPane, in which we plan to display the documents, and the JScrollPane, which provides scrolling skills for our browser. We place the JEditorPane into the JScrollPane. Now they can work together as a team.

We add another JEditorPane component to the top of the window (North). This component contains a Web page with control-links. The constructor takes the initial URLs as parameters and creates a GUI in several lines. We set the JEditorPane objects display and controls. Then we create a ContentPane object to hold all the JFrame components. We place the objects in the center and at the top of the content pane, respectively.

Page 38: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

ServiceBrowser at Work (2)There are several lines of calculations in which we set the component sizes based on the client screen resolution surveyed by the Toolkit.getDefaultToolkit().getScreenSize() method.

The constructor uses the image URL to load the logo icon and set the icon on the frame, to the left of the frame title. The program sets the title of the frame to the initial URL of the page that will be displayed first. The link event handler will continue this tradition, providing the current URL as the frame title each time a new link is activated.

The constructor finishes its GUI work by enabling the link handler, setting the display and controls pages, and finally, making the window visible. Note that the single setPage() method of the JEditorPane loads the page from the Internet or a local computer and displays the page.

The ServiceBrowser can also provide custom services that are not provided by any browser. We can request such services with URL - instructions that begins with the “service://” protocol instead of standard “http://” or “ftp//” or “file://” protocols. The link with this instruction will look like this:

<a href=service://[service instruction for execution]>Service request name</a>

Page 39: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

ServiceBrowser at Work (3)The hyperlinkUpdate() method is the required implementation of the HyperlinkListener interface that is responsible for handling link events. The method considers the type of event first. The HTMLFrameHyperlinkEvent is a notification about the link action. We can use this notification to retrieve the document for some analysis, but this is not the primary function of this method.

The primary function of the handleEvent() method is as a regular HyperlinkEvent that happens when a user clicks on a link. The program tries to retrieve a link URL and act upon the URL instructions. If this is a regular link that points to some web of local files, the program loads such a file and shows its content in the display window.

The most important case is when the instruction starts with the service:// string. This means that this is not a regular URL schema like http://, file://, or ftp://.

The service:// is the beginning of our service instruction that can be interpreted and performed in our own custom way. This extends ServiceBrowser’s functionality beyond by the functions embedded in the source code of this class. Unlike a lot of applications and browsers, the ServiceBrowser is just an engine able to perform any integration-ready service. The presentation layer of the ServiceBrowser is also not defined by the source code. The screens and controls are driven by HTML descriptions.

In Chapter 7, of the book “Integration-Ready Architecture and Design”, ISBN 0521525837 I discuss the XML browser driven by XML scenarios. The scenarios would describe GUI as well as program functionality.

Page 40: © ITS, Inc. Jeff.Zhuk@JavaSchool.com Java Graphics Learn Java Applet and User Interface AWT Swing

© ITS, Inc. [email protected]

SummaryBuilding a Swing GUI

Start with top-level containers (JFrame, JApplet, JDialog, and JWindow)

Create lightweight components (such as JButton, JPanel, and JMenu)

Add lightweight components to a content pane associated with a top-level container

Swing components are subclasses of the JComponent Class that provide:Borders Double buffering Tool tips Keyboard navigation Application-wide pluggable look and feel

JEditorPane and ServiceBrowser