Scrigroup - Documente si articole

Username / Parola inexistente      

Home Documente Upload Resurse Alte limbi doc  

AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows
WordXml

AspAutocadCDot netExcelFox proHtmlJava
LinuxMathcadPhotoshopPhpSqlVisual studioWindowsXml

Creating GUIs Basic Concepts

java

+ Font mai mare | - Font mai mic




DOCUMENTE SIMILARE

Trimite pe Messenger
Blocking: Becoming blocked
Text processing: Extracting code listings
Coding style
Using Sets
Network And Sockets
Date And Advanced Classes
Name hiding
Sharing limited resources: Improperly accessing resources
The twist - Method call binding
Java 1.1 IO streams: Sources and sinks of data





Creating GUIs Basic Concepts

Overview of GUIs

A GUI has two facets. One facet is all of the visual elements that are presented to the user. Think of this as the presentation layer. In a Web browser, the information presented to a user includes all visual elements such as text information, graphics, images, and video clips. Web browsers also provide menus, selection buttons, scrollbars, and text input boxes. The other facet is the programming that is associated with a GUI. This provides user–interaction functionality. For example, when the scroll bar is used, the information on the page changes. When a button or menu item is selected, some action occurs. This is the functional facet of a GUI.

The Java API provides a rich selection of classes to create the visual elements of a GUI and its functional facilities. This module explores the AWT and the Swing API of classes.

Numerous classes are available for a programmer to use. The large selection can make it difficult to decide on the best choices. This module provides an overview of the most common classes used to build GUIs. After reviewing the classes, the sequence of code that will create these GUIs may not be intuitively arrived at. Students will learn some very simple steps that are used to create, display, and program functionality for a GUI.

The model view controller pattern

Much of the interaction between a program and a user has been through the use of the System.in and System.out objects. A Console class has been provided to make user input and output interaction easier for students to program into their classes. In most real-world applications, such interactions are impractical. Program users expect more graphical representations of data and input interactions. Users expect to find a box on a screen to input data, a button to activate actions, scroll bars to view large amounts of information, and progress charts or bars that inform them of the progress of activities. Users also expect to see pictures and images, hear sound, and view video clips.

Creating classes that will draw images, play digitized sounds, and show movement of text and graphics can be very daunting. The Java platform provides a set of APIs commonly known as the Java Foundation Classes that provide many predefined programs that draw graphics and manage user interactions. The Swing classes can also be used to create graphical components. Much like building blocks, these classes can be used to make customized user interfaces, or screens. These are commonly known as GUIs.

To program a GUI, students must understand the following:

  • Event-driven programming
  • Model View Controller pattern
  • GUI terminology

All input and output should pass through the program GUI. The GUI consists of what a user will see on the screen and the code to process user actions. These can include moving a mouse over an object, selecting an item from a menu, entering text in a box, pressing a graphic that resembles a button, or closing and resizing a window. These represent a few of the possible user interactions that the code must be prepared to handle.

GUI programs are event driven. The user initiates an action by pressing a key on the keyboard or clicking a mouse. The GUI program must always be responsive to user input and take directions from the user.

In designing a GUI, keep in mind these principles:

  • Users initiate all actions.
  • Users must be able to initiate an action and receive a reasonable response.
  • GUIs display graphical objects that suggest actions that the user can perform.
  • GUIs provide responses when a user initiates an action.

To implement these principles, students need to master event-driven programming. They must design classes and write code that listens for events or actions initiated by a user and then responds to these actions.

In Java, events can be associated with GUI components and non-GUI components. One such example is an application that includes a class that observes network connections and notifies the Client class when the network connection is closed, or a class that observes writing data to a file and notifies the Client class when the file is closed. Figure 1 demonstrates a simple program that responds to interaction with a button. Press the button labeled “Press Me”. Note the changes in color on the Screen title. These changes occur because the user interacted with a GUI component, which was coded to respond with color changes.

To be consistent with object-oriented design, separate the program GUI classes from the program processing classes. The program should use one class to present the graphics, another class to process the data, or user input, and one class to handle the events that occur with user interaction.

For example, a program that allows a customer to withdraw money from an account will have a GUI class to present the window for a user to input a customer id, account information, and the amount to be withdrawn. A button on this screen could be used to initiate the withdrawal process. The Customer class contains the account information and a method to access account data. The Customer and the Account classes form the model or the Business classes. The GUI that displays the screen is the view and the class that handles interaction with the button is the controller. The controller provides the connection between the model and the view.

This design of classes separates the code that presents the data as part of one class from the code that holds the data in another class and the code that controls the transfer of data between the user and the model in yet another class. This represents an implementation of the Model View Controller Pattern.

The advantage of this model is that the same model can be presented in different views, or GUIs. For example, the Customer objects can be connected to a Teller GUI or an ATM GUI. A single Customer class holds the data for the customer, but there are different View and Controller classes for handling the Teller and ATM implementations.

Components form a major part of a GUI. Java components are pre-defined standard elements such as buttons, text-fields, frames, windows, labels, scrollbars, menus, menu items, text areas, and dialog boxes. These are shown in Figure 2.

The display space on the screen is also a component. Like all GUI-based applications, the Java display space is a window. Some windows have additional graphics features and are known as frame windows. Frame windows have a title, a border, and buttons for closing, minimizing, and maximizing the window. This is shown in Figure 3. They can also contain a menu bar.

Some components are used to hold other components. For example, a dialog box can hold a label and a button. A window can hold a dialog box and other buttons and components. Components that can hold other components are called containers. This is shown in Figure 4. The window is a container, since it holds two panels. Each panel is also a container, since it holds some text.

In response to popular demand to support GUIs, the Java platform provides the Java Foundation Classes. There are five APIs that form the Java Foundation Classes. These are shown in Figure 5.

 

This course will explore two of the Java Foundation Classes. These two classes are the Abstract Window Toolkit (AWT) API and the Swing API. These form the foundation of classes used to create GUIs.

Apply inheritance concepts

Computer users now demand that application programs provide GUIs. When a program has a GUI, a large portion of the code services the GUI. It builds the GUI and repaints graphics when the windows are moved or when new information needs to be displayed. Programming for the GUI can sometimes become the largest part of the code for an application. This is shown in Figure 1.

 

This section explores the AWT package and Swing package. These contain all of the classes for creating user interfaces and for painting graphics and images. A user interface object such as a button or a scrollbar is called a component. Figure 2 shows some of the classes that form the AWT API. The Component class is the root of all AWT components. All AWT components share the properties described in the Component class. A container is a component that can contain components and other containers. A container usually has a layout manager that controls the visual placement of components in a container. The AWT package contains several layout manager classes and an interface for building a layout manager.

Many of the classes in the Swing API implement these classes as the peer-component. The AWT set of classes are also known as heavyweight components. This term is applied to these classes because they are dependent on the operating system layer. Although the Java code is platform independent, at runtime the behavior of these classes is very platform dependent. GUIs created with these classes may look different on different platforms.

Most GUI programming in Java uses the Swing API. This is shown in Figure 3.

There are several reasons for this. The foremost is that the Swing set of classes are lightweight components. The Swing API provides lightweight components that, for the most part, work the same on all platforms. This API provides a wider range of components to display emerging GUI technologies such as a table of data, images, and Sliders. Swing classes use a special facility called the look-and-feel feature. This feature allows programmers to either set a look and feel for a GUI that resemble the look and feel of some common operating systems, select a generic type, or use some other custom look and feel. Many of the AWT components are provided through classes that have the same name, with the letter J. For Example the Button class in AWT has a corresponding JButton class in swing. The Swing set of classes provides more sophisticated GUI capabilities than those of AWT. Swing classes build on the features of the AWT classes. Understanding the AWT classes prepares students for the use of Swing classes. The Sun Microsystems Java website listed below has a tutorial on the use of Swing. Students may wish to go through this tutorial to explore additional possibilities of using the Swing set of classes.

The AWT and Swing hierarchy

The AWT and Swing classes can be viewed under several categories:

  • These classes draw graphics or manipulate images:
    • Graphics
    • Image
    • Insets
    • Point
    • Polygon
    • Rectangle
  • These classes can be used to position visual elements:
    • BorderLayout
    • CardLayout
    • CheckboxGroup
    • FlowLayout
    • GridBagLayout
    • GridLayout
  • These classes can be used to change properties of visual elements:
    • Toolkit
    • Color
    • Font
    • FontMetrics
    • CheckboxGroup
  • These classes create graphical components:
    • MenuComponent or JMenuComponent
    • Component
    • MenuBar or JMenuBar
    • MenuItem
    • Menu
    • PopupMenu
    • CheckboxMenuItem
    • Button or JButton
    • Canvas
    • Checkbox
    • Choice
    • Label
    • List or JList
    • Scrollbar
    • TextComponent
    • TextArea
    • TextField
  • These classes can hold other components or containers:
    • Container
    • Panel or JPanel
    • Window JWindow
    • ScrollPane
    • Dialog
    • Frame or JFrame
    • Applet (java.applet package) or JApplet
    • FileDialog

Figure 1 illustrates the AWT hierarchy and presents a map of the classes. Some classes that create GUI components are shown in this figure. The root of all of these classes is the Component class. All of the other classes inherit from this class. Recall from module 8 that subclasses inherit non-private methods and data from the parent class. When using these classes, always read the list of inherited methods and data. Most components inherit from the Component class. MenuComponent is the superclass for MenuBar and MenuItem.

Figure 2 shows a sample of Swing components. To explore further details on the demonstration of the Swing classes, locate the folder j2sdk1.4.1_01demojfcSwingSet2. This folder should be part of the documentation that was downloaded with the SDK. The demo folder contains many Java example. The SwingSet2 demo launches an HTML file that displays the swing components.

The AWT classes

Programming for a GUI may become the largest part of the code of an application. In order to create GUIs, classes from the java.awt, java.awt.event, javax.swing.*, and java.swing.event.* packages will be used. The module content and labs will require a significant amount of time to be spent researching the classes in these packages.

When creating applications that include GUIs, include the import statements shown in Figure 1 in the source file. Recall from module 6 that import statements must follow package statements and precede all other code. Import statements provide a path for the compiler and the run-time JRE to locate and load the classes used in the code. These two lines will be most commonly found at the start of GUI source code.

For the purposes of creating GUIs, the extensive set of classes that make up the AWT and Swing can be categorized as classes that manage and create graphics and classes that create components. Components are objects that display a graphic image and can monitor user interactions with an image.

GUIs can be used in applications, which are standalone Java programs, and also in applets, which are Java programs that run inside a Web browser.

The java.applet package contains the Applet class, and the javax.Swing package contains the JApplet class, both of which provide a standard interface between applets and their environment. An applet is a small program that is intended not to be run on its own, but rather to be embedded inside another application. Applets typically run within Web pages in Web browsers that can read HTML tags. The creation and use of applets will be explored in a later section.

Another categorization of the GUI classes is shown in Figure 2. Reading from left to right, the first box shows the classes used to create graphic objects. These are not GUI components.

These classes include the following:

  • Graphics class — The Graphics class is the abstract base class for all graphic contexts and is used to draw onto on-screen and off-screen components.
  • Image class — The abstract class Image is the superclass of all classes that represent graphical images. The image must be obtained in a platform-specific manner.

The second box refers to the classes that are used to manage the layout of the graphic elements:

  • BorderLayout class — A BorderLayout lays out a container and arranges and resizes its components to fit in five regions, which are North, South, East, West, and Center. When adding a component to a container with a BorderLayout, one of these five names can be used to control the part of the container to which the component gets added. If a region is not specified, the component will be added to the Center.
  • FlowLayout class — A FlowLayout arranges components in a left-to-right flow, much like lines of text in a paragraph. FlowLayouts are typically used to arrange buttons in a panel. It will arrange buttons from left to right until no more buttons fit on the same line. When this point is reached, the buttons will be continued on a new line. Each line is centered.

The third box refers to the classes that set the properties of graphics and GUI components:

  • Color class — This class encapsulates colors using the RGB format. In RGB format, the red, blue, and green components of a color are each represented by an integer in the range 0 to 255. The value 0 indicates no contribution from this primary color. The value 255 indicates the maximum intensity of this color component.
  • Font class — A class that produces font objects.

Figure 3 shows the most commonly used GUI components. These components were created using the classes in the java.awt package.

An example of a commonly used GUI component is a window. A frame is a window that has a title, a button to maximize or minimize, and a button to close the window. Another example is a button, which is usually a rounded polygon shaped figure that a user clicks with a mouse to initiate some action. The text box is a GUI component that accepts input from the user as text. The text boxes can be a single line box, which is also known as a TextField, or a multi-line box with or without scroll bars, which is known as a TextArea. Other components include menu items in a menu bar and choice boxes that present a list of choices. GUIs can be used to display custom forms.

In Figure 4, a word processing program uses this form to display information about the document.

GUIs also form the displays seen in browsers and World Wide Web documents. This is shown in Figure 5. Each of these examples show the use of components to provide the user a way of interacting with the information. Nothing happens until the user interacts with the GUI.

Many of these components have already been encountered. Screens can now be created and components can be placed in design layouts that meet the needs of a programmer. A programmer can program functionality for these components by creating classes that handle events generated by user interactions with these components.

GUI Component classes include the code to draw a graphic image that is visible on the screen and public methods to provide user interaction functionality. The most common methods encountered in the GUI Component classes are as follows:

  • add() – add components to containers
  • remove()
  • setText() – set the text value, or contents, for text components such as text input fields
  • getText()
  • setLabel()
  • getLabel()
  • setFont() – set the font for any text
  • setBackground() – set the color of the background
  • setForeground() – set the color of the foreground

Most components need a surface on which to be displayed. Among the Component subclasses is a Container class. All classes that derive from the Container class serve as containers for other components or other containers. These containers will display the components added to the container.

Among the containers that can hold other components are the Panel, Applet, Dialog and Frame classes. Each of these containers implement enhancements over the class they derive from. All of these classes except for the Panel class will display the components directly. The Panel class is a free-floating container and must be added to another container in order to be displayed. 

Steps to Create a GUI

The steps to create a GUI

Selecting the appropriate classes for the creation of GUIs can be a daunting prospect, especially since so many choices are available. Questions about whether to use the AWT or Swing, a choice component or a pull–down list, a TextField or a TextArea, and how much space to allow for user input must be considered. All of these considerations are part of the design phase for a GUI. The design of effective GUIs requires an understanding of how users will interact with the application. Students interested in learning more about designing effective user interfaces should read the writings of Jakob Nielsen.

When a design has been developed for a GUI, the next step is to code the class that will display the appropriate components and respond to user interactions. Students will find that a systematic and consistent approach to coding Java statements for displaying GUIs eliminates a lot of errors and allows for easy changes and enhancements to the GUI.



The steps to creating a GUI are shown in the figure. Note that the first step is the design of the GUI. As students move to the GUI coding stage, they begin by selecting the type of surface or container that will display the GUI. This is often a window or a frame. After the container is selected, components are created. The creation of components and the selection of layout managers can be done in any sequence. However, the assembling of the different layers of the GUI and the placement of the components requires a sequence. The sequence by which the components and containers are assembled will affect whether or not the GUI displays as expected.

The class that will display the GUI can either be a component that extends from one of the components, a component such as a frame or window, or it can contain references to the component “ has a component”. It is more common to see classes extend from the containers Window, Frame or Applet, JFrame, JWindow, or JApplet.

When creating GUIs follow the steps listed in Figure 1. The sections that follow will detail each of the steps and sample code for each step.

Step 1: Designing the class

Designing GUIs requires a great deal of interaction with the users of an application. A good GUI results in effective user interaction. The goal is not to clutter up the screen with every component, but to break up the screen into separate areas. Draw a rough sketch of the GUI. Many commercial Integrated Development Environments (IDEs), such as the tool BlueJ, provide a visual component editor. These editors will let a programmer place components and move them around. These programs are GUIs for creating other GUIs.

One technique to use is to layer the GUI into panels. Then each panel can be designed with different functionality. Panels are containers that can hold other panels and other components. Panels are an effective way of sectioning up the screen area, which is also known as display real estate.

Figure 1 shows a simple GUI application to send and receive messages that is similar to a chat window. This is not a fully working application because it does not have the network connectivity to send messages to other computer users. The purpose of this example is to provide a simple application to illustrate the concepts in this module.

1: represents a Frame (messageWindow) that holds the messageBase Panel and the messageAction Panel

2: represents a Label (sentLabel) on LabelArea Panel

3: represents a Label (recdLabel) on LabelArea Panel

4: represents a TextArea (sent) on messageDisplay Panel

5: represents a TextArea (received) on messageDisplay Panel

6: represents a TextField (message) on messageAction Panel

7: represents a Button (send) on buttonArea Panel

8: represents a Button (read) on buttonArea Panel

9: represents a Button (clear) on buttonArea Panel

10: represents a Button (exit) on buttonArea Panel

Based on user input, a rough sketch of the MessageGUI Window is shown in Figure 2. There is an area for displaying messages that have been sent and an area for displaying messages received. This is a chat window. The expectation is that one or two sentences may be transmitted back and forth. The users have asked for a window in which a message can be typed in one area and an immediate response can be displayed in another area. The window will include buttons to allow the user to command the sending, reading, and clearing of messages, as well as exiting from the program.

Identify the components used in the diagram for Figure 2. Note the many layers that are required to create this GUI.

Step 2: Deciding on containers

Container selection determines the type of basic surface that displays the GUI. A surface is not the physical screen or monitor, but the area on the screen and monitor where the GUI will be displayed. These are generally referred to as windows. GUI windows are of several different types. Widows that provide scrollbars, minimize, maximize functionality, and size-change functionality are used commonly as top-level surfaces. Additionally, windows to present messages, warnings, and other information such as dialog windows may only have the functionality to close the window and none to change its size or minimize it. In Java, two other containers are available. Containers such as Applet or JApplet can only be displayed in a browser. Panel or JPanel can only be displayed inside another container. The selection of the proper top-level container is important for the creation of an effective GUI.

The Containers used in the MessageGUI application are shown in Figure1. This section discusses the properties of these containers and the appropriate selection of these when used to hold and display other components.

There are two main types of containers. They are Window and Panel or JWindow and JPanel. Recall that almost every AWT component has a corresponding Swing component that starts with the letter J.

A Window is a freestanding native window on the display that is independent of other containers. There are two important types of Window or JWindow. They are Frame, JFrame, Dialog, and JDialog. Dialog and JDialog do not have a menu bar. Although they can be moved, they cannot be resized. Frame is a Window with a title and resizing corners. Frame is a subclass of Window. Frame inherits from Container so a programmer can add components to a Frame using the add method. The constructor Frame(String s) in the Frame class creates a new, invisible Frame object with the title specified by the String object referenced by the variable s. Add all the components to the Frame while it is still invisible in Figure 2.

With Swing components the visual elements, or the components that will be displayed, are not added to the top-level container directly. Unlike AWT, where top-level containers have access to the underlying hardware facility for displaying its components, Swing components require another container called the ContentPane to place elements. The ContentPane serves as the container and has a reference to the underlying hardware resources to render the GUI. ContentPane objects are part of the top-level JFrame or JWindow object, and are obtained by retrieving it from these containers using the getContentPane() method. The getContentPane() returns the contentPane object of the type Container for this frame. This is shown in Figure 3.

Figure 4 shows some of the common methods of the Window, Frame, Dialog, and Panel classes, and methods in the corresponding Swing classes.

Frame and JFrame are top-level containers extending from Window and JWindow with a title and a border. The default layout for a frame is BorderLayout. Layouts determine the particular methodology used to place components on a container. All containers have default layout features, which can be changed.

A Dialog is a top-level Window with a title and a border that is typically used to take some form of input from the user. The default layout for a dialog is BorderLayout. A dialog must have either a frame or another dialog defined as its owner when it is constructed. When the owner window of a visible dialog is hidden or minimized, the dialog will automatically be hidden from the user. When the owner window is subsequently re-opened, then the dialog is made visible to the user again.

A Panel is a free-floating container and must be displayed on another container such as a Window, Frame, or Dialog, or inside of a Web browser window in an Applet. A Panel identifies a rectangular area into which other components are placed. This is shown in Figure 5.

Panel is the simplest container class. A panel provides space in which an application can attach any other component, including other panels. The default layout manager for a panel is the FlowLayout layout manager.

The fact that a container can hold components and other containers, is fundamental to building complex layouts. The Panel container is used to layer a GUI display. Figure 6 shows the different containers used to display this GUI. In the chat window, several container surfaces were employed in layers stacked on top of each other to display each of the components.

This separation of GUI components to different containers allows a programmer degrees of granularity to manage one or more components without unduly changing the location or size of others. The chat window uses the following containers:

  • A Frame forms the base to display all the components.
  • Two large Panels are placed on the Frame. They are messageBase and messageAction.
  • The Panel messageBase is used to contain two additional panels, which are labelArea and messageDisplay.
  • The labelArea Panel will display two Label objects.
  • The messageDisplay Panel will display two TextArea objects.
  • The Panel messageAction is used to contain the buttonArea Panel and to display a TextField.
  • The buttonArea Panel will display the four Button objects.
  • Note that what seems like a simple GUI required several layers of panels to display the components that are desired.

In designing a GUI, a programmer needs to consider the context in which the GUI will be displayed. Will the GUI be displayed in a Web page or as part of a stand-alone application? Java provides the Applet class to display GUIs in Web pages. However, the context may be a stand-alone program that is not part of a Web page. In this case the Frame class can build a window on the screen to display components. What if the programmer is expected to create a GUI that can be displayed in either? In this case, the programmer can select the Panel class as a container for all the GUI components. An object of this class can then be displayed either in a Frame or an Applet. This provides the most flexible reuse of code.

Creating the containers

As mentioned previously there are a number of containers that may be used in a GUI. The first step is to select the top-level container. A Panel and its subclasses cannot be selected as top-level containers. In general, containers that subclass a Window should be used. A Frame or JFrame is the most common choice. Although Panels cannot be used as top-level containers, since they are free floating windows and require a Window or another application to display their components, GUIs that are designed in a modular fashion, may be defined as Panels. For example, in the messageGUI example from the previous section and in Figure 1, the top-level container could be a Panel. In this case, the class that renders this GUI will require a Frame or Window to display the Panel.

Figure 2 shows the different options for creating a top-level container. The class is a Container, or the class has a reference to a container. Note that when the class contains a reference to a Container, the container is generally instantiated in the constructor. When a class is a Container, instantiating the class launches the container.

Creating the components

The definition of the GUI class includes the declaration of the components to be displayed in the GUI as attributes of the class. The component references can be created and then each component object can be constructed, or the reference and the object can be created at the same time. If a programmer wishes to set properties of each component using the information provided to the constructor, then two steps would be used, one to declare the component reference and the other to create the object in the constructor. Alternatively, the component can be instantiated as part of the declaration of the component as an attribute of the class. This is shown in Figure 1.

The example in Figure 2 uses the sketch designed in the previous section and creates the references for all of the components. The components used for this GUI are Button, Label, TextArea, TextField, Panel, and Frame. Locate the documents for each of these classes in the API documents before reading any further. In this section the basic properties of the AWT version of the components are described. Locate the java.swing package in the API and review the corresponding classes in the swing package.

1 /**

2 * The MessageGUI class presents a user interface for

3 * sending and receiving messages

4 *

5 * @author Cisco Teacher

6 * @version 2002

7 */

8

9 //Required import statements

10

11 import java.awt.*;

12 import java.awt.event.*;

14 public class MessageGUI implements ActionListener,WindowListener

15 Fig 2

The Button class provides two constructors and several methods. Figure 3 shows the Button class API. The Button class has several useful methods for programming event handling. These methods include setLabel(String s) to change the text that displays as the label on a button and setActionCommand(String s) to set a specific String that represents an action on a button. In addition to these are the methods used to add a listener to a component or remove a listener from the component. The Button class extends the component class. Review the methods that it inherits from the Component class.

A button on the screen has three elements:

  • The image of the button, or the graphic
  • The code that monitors the interaction of the user with the button
  • The code that performs some action based on the interaction

The behavior of the button can be controlled by the use of various methods provided in the Button class. Figure 2 shows a list of some of the methods and what they do. The color of the button can be changed with the setBackground() method. The color of the text can be changed with the setForeground() method. The font for the label can be changed with the setFont() method.

The Label class is used to display text as labels on the screen. A label displays a single line of read-only text. Labels can be changed using the setText() method. This is shown in Figure 4. The text can be changed by the application, but a user cannot edit it directly.

The properties of the label can be changed by the use of various methods provided in the Label class. Figure shows a list of some of the methods and what they do.

The TextComponent class is subclassed into TextField and TextArea. The TextArea is an area in which the user can enter several lines of text. TextAreas can be set to have a length of rows and number of columns. This is shown in Figure 5. Vertical and horizontal scroll bars can be displayed to the right and bottom, respectively, of the TextArea. A TextField is a single line of text. This is shown in Figure 6. The size of the field can be set. When a user presses Enter, the input to the TextField is considered complete.

There are several other components that may be chosen. Each of the components will include constructors and methods to add listeners to the components. Only the most commonly used components have been selected to be used in this application.

There are at least two approaches possible for the creation of GUI components. Some programmers like to define the references to GUI components first, define a constructor that calls a build() method, and build the GUI in this method. Others prefer to build the GUI in the constructor for a class. Either method is acceptable.

Two examples of code for the MessageGUI class are presented. The first builds the GUI in the constructor. The second calls the build() method in the constructor. Note the placement of the code in Figures 7 and 8. Creating an instance of the MessageGUI class will automatically launch the GUI regardless of which coding pattern is used.

2 * The SimpleGUI class presents a simple user interface

3 * @author Cisco Teacher

4 * @version 2002

5 */

6

7 // Required import statements

8

9 import java.awt.*;

10 import java.awt.event.*;

11

12 public class SimpleGUI extends WindowAdapter

45

46 public void windowClosing(WindowEvent e)

50 }

2 * The SimpleGUI2 class presents a simple user interface

3 * @author Cisco Teacher

4 * @version 2002

5 */

6

7 // Required import statements

8

9 import java.awt.*;

10 import java.awt.event.*;

11

12 publicclass SimpleGUI2 extends WindowAdapter

39

40 void build()

41

54 publicvoid windowClosing (WindowEvent e)

58 } // end class

Layout managers

Each container object will add other components or containers when the add() method of the container is called and a component object reference is passed to it. Each container has a default LayoutManager object that sets the position for displaying each component. LayoutManager objects determine location and size based on predefined instructions. A layout manager governs the layout of components in a container. Each container such as Panel or Frame has a default layout manager associated with it that can be changed by calling the setLayout method. The layout manager is responsible for deciding the layout policy and size of each child component of the containers. The default layout manager for Panel is FlowLayout and for Frame it is BorderLayout.

There are four ways that a programmer can select a layout manager:

  • Use the default layout manger for a particular container. .
  • Select an alternate layout manager from the predefined layout manager classes using the setLayout() method. For example, setLayout(new BorderLayout()) or setLayout(new GridLayout(2,3)) can be used.
  • Create a custom layout manager extending from LayoutManager. Set the layout to this custom layout manager.
  • Place each component using setLocation(). This will require that the default layout manager not be used by using the setLayout(null) option.

The layout managers manage components according to the rules shown in Figure 1. The selection of the proper layout manager can make placing the components, controlling the resizing, and movement of the components a lot easier as well as ensuring platform independence.

The BorderLayout manager breaks up the area into five regions. This is shown in Figure 2.

The layout manager controls the sizes of the regions. Each component is placed in the entire region. The north and south regions will maintain the height of a component and expand its width to occupy the entire region. The east and west will maintain the width, but increase or decrease the height to occupy the whole region. When objects are placed in only one region, the center region takes up the rest of the space. When selecting the BorderLayout manager, be sure to use the center region for at least one of the components. This is shown in Figure 3.

The setLayout(new BorderLayout()); method will create a new instance of the BorderLayout object for the specific container. The add(Component, Region); statement adds a specific component in the region specified.

The sample code in Figure 4 implements a simple BorderLayout.

1 import java.awt.*;

2 public class ButtonDir extends Panel

11 public static void main(String[] args)

19 }

The FlowLayout manager places the components from left to right and top to botom. In Figure 5, it is shown that resizing the window does not change the size of the components.

The default alignment is centered. The constructor for the FlowLayout manager accepts settings for the behavior of the layout manager. The FlowLayout manager has the following properties:

  • The default layout is used for the Panel class.
  • Components are added from left to right and top to bottom.
  • Default alignment is centered to the area. This can be changed.
  • It uses the components preferred sizes.

Note: Resizing the window will not change the size of the components.

The constructor arguments for the FlowLayout manager are described in Figure 6.

1 //setLayout(new FlowLayout(int align,int hgap,int vgap));

2

3 //The value of align must be FlowLayout.LEFT, FlowLayout.RIGHT, or

4 //FlowLayout.CENTER

5

6 //The following statement constructs a FlowLayout with right alignment,

7 //a 20 unit horizontal gap and 40 unit vertical gap

8

9 setLayout(new FlowLayout(FlowLayout.RIGHT, 20, 40));

10

11 //setLayout(new FlowLayout(int align))

12

13 //The default gap is a five unit horizontal gap and five unit vertical gap

14

15 //The following statement constructs a FlowLayout with left alignment, a 5

16 //unit horizontal gap and a 5 unit vertical gap

17

18 setLayout(new FlowLayout(FlowLayout.LEFT));

19

20 //The default alignment is FlowLayout.CENTER

21 //The folowing statement constructs a FlowLayout with a centered alignment,

22 //a 5 unit horizontal gap and a 5 unit vertical gap

23

24 setLayout(new FlowLayout());

The sample code in Figure 7 implements a simple FlowLayout.

s

1 import java.awt.*;

2 public class ButtonOnFrame extends Frame

13 public static void main(String[] args)

19 }

In addition to the FlowLayout and BorderLayout, the GridLayout manager provides more control over the location of components. This is shown in Figure 8.

The properties of a GridLayout manager are as follows:

  • Components are added left to right and top to bottom.
  • All regions are equally sized.
  • The constructor specifies the rows and columns.

The sample code in Figure 9 implements a simple GridLayout.

1 import java.awt.*;

2 public class ButtonGrid extends Frame

12 public static void main(String[] args)

18 }

Selecting specific panels and layouts for each of the panels can further refine the chat window class. Selecting the proper combination of panels, frames, and layout managers provides greater control over the components on the screen. This is shown in Figure 10.

The selection of a layout manager occurs with the use of the setLayout() method of the container. The highlighted code shows the use of this method in the MessageGUI class. This is shown in Figure 11.

1 /** The MessageGUI class presents a user interface for

2 * sending and receiving messaages

3 *

4 * @author Cisco Teacher

5 * @version 2002

6 */

7

8 //Required import statements

9

10 import java.awt.*;



11 import java.awt.event.*;

12

13 public class MessageGUI implements ActionListener, WindowListener

66

67 //more statements

68 }

Once the layout managers have been selected, components can be added to the containers. The sequence in which they are added is critical. Take time to review the code and the sequence in which the components are added.

It is also possible to set the absolute position of the graphical components in this way:

Set a null layout manager for the container with setLayout(null).

Call setBounds() or reshape() for each component, passing a bounding rectangle in pixel coordinates. This can be done in the constructor, or in the paint() method. This approach may not be portable across all platforms.

Some GUI builders use this approach extensively, but this is usually not the best way to generate code. More useful GUI builders will use the GridBagLayout instead.

The CardLayout manager is very useful for managing Panels that will be stacked on top of each other. This layout manager will display a different Panel as requested. Much like a deck of cards, the CardLayout manager can display one card at a time. The card here is represented by a Panel with all of its components. The design of a GUI using the CardLayout manager requires the creation of a base Panel to which the layout manager is assigned. Then each of the display Panel references are added to the layout manager. The methods show() and add() are used to create a CardLayout managed display.

The table in Figure 12 presents a comparison of the layout managers.

Assembling the components and containers

When the components have been instantiated and the layout managers have been selected for each container, the next step is to add components to each container. This should be done in a sequential manner. When using many panels in layers, begin with the panels that will contain the visible elements. Create the panels that will contain the buttons, TextFields, labels, and other visual display elements. Then assemble the next layer of the panel. At each step, the add method of a container is called to add the components to the container.

Figure 1 shows the statements required to add components to panels and panels to frames. The examples use AWT-based components. The result of this code is displayed as a GUI.

Figure 2 shows the same code used in a class that is a frame. The class AWTExample2 is a frame, so the method setTitle is used to set the title of the frame. Since this class is a frame, the add, pack, and setVisible methods are called directly, without the use of any object reference as in the previous example.

1 /**

2 * Java class AWTExample2.java

3 * Class demonstrates the aseembling of panels and components in a frame

4 * @author Cisco teacher

5 * @version April 2004

6 */

7 import java.awt.*;

8 import java.awt.event.*;

9

10 publicclass AWTExample2 extends Frame

26 publicvoid launch()

44

45 publicstaticvoid main(String args[])

48

49

50 }

Figure 3 shows the statements required to add components to panels and panels to frames. Unlike the AWT Window containers, swing requires the use of the contentPane object to assemble the GUI. Note that the contentPane object is retrieved by calling the getContentPane() method on the frame. Also note that in the launch method, the add methods are called on the contentPane and not on the actual frame. The sizing and making the frame visible are called on the frame directly, and not the contentPane.

1 /**

2 * Java class SwingExample1.java

3 * Class demonstrates the aseembling of panels and components in a frame

4 * @author Cisco teacher

5 * @version April 2004

6 */

12 publicclass SwingExample1

31

7 import java.awt.*;

8 import java.awt.event.*;

9 import javax.swing.*;

10 import javax.swing.event.*;

32 public void launch()

50

51 public static void main(String args[])

54

55

56 }

Figure 4 shows the same code. In this example the class is a JFrame. The calls to the methods getContentPane(), pack(), and setVisible() do not need an object reference.

1 /**

2 * Java class SwingExample2.java

3 * Class demonstrates the aseembling of panels and components in a frame

4 * @author Cisco teacher

5 * @version April 2004

6 */

7 import java.awt.*;

8 import java.awt.event.*;

9 import javax.swing.*;

10 import javax.swing.event.*;

11

12 public class SwingExample2 extends JFrame

31 public void launch()

49

50 public static void main(String args[])

53

54

55 }

Sizing components and containers

A layout manager determines the position and size of a component in a container. A container keeps a reference to a particular instance of a layout manager. When the container needs to position a component, it invokes the layout manager to do so. The same delegation occurs when deciding on the size of a component. The layout manager takes control of all of the components within a container. It is responsible for computing and defining the preferred size of the component in the context of the actual screen size by using FlowLayout(). For example, the preferred size of a button is the size of the label text plus the border space and the shadowed decorations that mark the boundary of the button. The preferred size is dependent on the platform.

Since the layout manager is responsible for the size and position of components on its container, the size and position should not be changed. If this is tried using methods such as setLocation, setSize, or setBounds, the layout manager will override the request. In order for these methods to size and position the components, the layout manager must be set to null using the syntax setLayout(null).

In addition to using the setSize() method, the pack() method can be used to place all the components within a small panel or frame. A call to the pack() method of a container does not change the placement of the components if a layout manager is installed. However the size of the components may be impacted by the use of the pack() method.  

Displaying the GUI

It is best to display the GUI after all of the components have been built and added to the Panels, Frames, and Windows. The method setVisible is used to display components. This method accepts the boolean value true to make the components visible and false to hide them. The setVisible method can be used on a specific component or on the base container that contains all other components. The MessageGUI class consists of a base Frame and messageWindow. The setVisible method of the messageWindow is called. When this method is called all of the components contained in the base Frame messageWindow are displayed on the screen.

At this stage, the GUI is mostly ready for launch and testing. The BlueJ swing classes will launch and students will be able to select the close window button and the window will close. This is because the functionality, or programming, to close the button is built-in to the basic definition of the container class. In the AWT example, this is not the case. When the GUI is launched, BlueJ must be shut down to close the window. Sometimes this may not work. If this occurs, locate the system status program such as a task manager and locate the GUI application and end the task.

Color

The color of a component is a property of the graphics of that component. The Java language provides the Color class in the AWT package. The Color class includes several constants that define the combination of red, green, and blue as integer values. Each integer value represents a specific color. To set the color of a graphic object, programmers can provide their own Color object or use one of the static final predefined objects of the Color class shown in Figure 1.

1 /**

2 * @author Cisco Tacher

3 * @version 2004

4 */

5 import java.awt.*;

6 import java.awt.event.*;

7 publicclass TestColors extends Frame

31 } // end class

// 1 Static final predefined objects of the Color class. Unlike the standard naming convention of using uppercase for //constants, these are all named in lowercase

A Color object can also be created using one of the constructors. For example, Color(int r, int g, int b) will create an opaque object with different intensities of red (r), green (g), and blue (b). The values for each integer are between 0 and 255. Some computers cannot display all of the colors. There are 16 million possible colors. Each computer will display the closest color it can.

Coloring text and objects requires some attention to the type of component being colored. Labels, Buttons, and TextFields can be set to different colors using the setBackground() and the setForeground() methods. The foreground changes the color of the text in a TextField object, the label of a Button object, or the text of a Label object.

When a user first starts drawing shapes, all shapes are drawn with a black pen. To change the color, an object of the type Color is used. Java uses the RGB model, which allows users to specify a color by the amounts of red, green, and blue that make up the color. The amounts are given as float values, and they range from 0.0f, color not present, to 1.0f, maximum amount of color present. Some of the predefined colors and their RGB values are shown in Figure 2.

Font

Fonts represent the technology for displaying symbols of the written language in different shapes, sizes, and styles. There are two terms frequently used to describe the features of fonts. They are character and glyph. A character is a symbol that represents items like letters and numbers in a writing system. When a character has been rendered, a shape is used to represent it. This shape is called a glyph.

A font is a collection of shapes for representing characters. A font can have faces such as heavy, medium, oblique, gothic, and regular. All of these faces have similar typographic designs. A font includes the shape or glyph, face, and size. The typographical design is known as the font family. Courier and Helvetica are examples of font family names.

A font is described by its face name, style, and point size. The name is one of the logical face names, such as Serif, Sans Serif, Monospaced, Dialog, and DialogInput, or the name of the typeface that is available on a computer, such as those shown in the table in Figure 1. Point size is the height of the characters in the font.

This table provides a comparison of the font family names used in Java across different OS platforms.

The font styles are plain, bold, and italic. Italic can be combined with plain and bold. The size of a string depends on the font face or the point size. The ascent of the font is the height of the largest letter above the baseline. The descent of the font is the depth below the baseline of the letter with the lowest descender. These describe the vertical extent of the string. The horizontal extent depends on the individual letters in a string. In a proportionally spaced font, different letters have different widths.

Fonts are set for the text of any component or graphics objects using Font objects. A Font object contains data regarding the font face, the style, and the size. There are three different names that can be obtained from a Font object. They are the logical font, the font face name, or the font name such as Helvetica Bold. The family name is the name of the font family that determines the typographic design across several faces, such as Helvetica. It is important to note that the font face name is the one that should be used to specify fonts. This name signifies actual fonts in the host system.

The Font class represents an instance of a font face from a collection of font faces. These font faces are present in the system resources of the host system. For example, Arial Bold and Courier Bold Italic are font faces. There can be several Font objects associated with a font face, each differing in size, style, transform, and font features. The getAllFonts method of the GraphicsEnvironment class returns all of the font faces available in the system.

Integer values represent the style of the fonts. The Font class stores data in static members to represent the font style. These integers are Font.ITALIC, Font.BOLD, and Font.PLAIN. These integers are combined to obtain combination styles such as italics and bold using Font.BOLD + Font.ITALIC. The Toolkit class can be used to obtain information about the fonts on the computer.

Font objects can then be used as arguments to the setFont() methods of components.

The font can also be set by obtaining the names of the fonts from the system and then using these to create a Font object.

A list of fonts available on a system can be obtained with the code shown in Figure 2.

The elements of the String array can be evaluated to determine the Font object to create. The String list also can be used to load a list of choices in a Choice component. The user can be presented with these, and the choice made could be used to create a Font object and set the text of some field or a label to this font.

Figure 3 shows the creation of font objects and the statements that apply these to the components.

2 * @author Cisco Teacher

3 * @version 2004

4 */

5 import java.awt.*;

6 import java.awt.event.*;

7 publicclass TestFont extends Frame

35 } // end class

Create graphics objects

Each component has a Graphics object, and any component has a canvas on which graphics objects can be drawn. Objects can be drawn on a panel, frame, or applet. The Canvas class is provided as a surface for drawing. Typically, a subclass of Canvas would be created and the paint() method would be overridden.

A Graphics object is an instance of the Graphics class. A constructor cannot be called to create a Graphics object. To create a Graphics object, there must be a context in which this Graphics object can be drawn. This is usually a Component such as a Panel. These classes provide the getGraphics() method, which provides the context of a graphic. The context is a surface on which images will be drawn. Without this surface, the images cannot be visible. In an applet, the getGraphics() method provides the applet surface as the context. In a frame, the Frame provides the context.

The Graphics class provides many methods to draw shapes. The table in Figure 1 shows the methods and a sample of the shape drawn.

In addition to the methods for drawing shapes, the clearRect() method can be used to draw what appears to be a clear, or empty, rectangle. The clearRect() method draws a rectangle using the current background color. This is what creates the appearance of an empty rectangle.

Two sample programs are provided here. The Monogram program is a simple applet that draws filled in ovals and rectangles. This is shown in Figure 2.

1 /**

2 * Java Program: Monogram.java

3 * @author Cisco Student

4 * @version 2002

5 */

7 import java.applet.*;

8 import java.awt.*;

9 import java.awt.event.*;

10

11 public class Monogram extends Applet

26 } // end class

The Skylined program sets an integer to count the number of times the button is clicked. For each even number, the colors of the shapes and the background of the graphic are changed. In this applet, the paint() method is called when the applet starts and when the actionPerformed method is executed. In this method, the paint() method is called so that the shapes can be painted with different colors, as shown in Figure 3.

2 * Java Program: Skylined

3 * @author Cisco Teacher

4 * @version 2002

5 */

6 import java.applet.*;

7 import java.awt.*;

8 import java.awt.event.*;

9

10 public class Skylined extends Applet implements ActionListener

21 /**

22 * @ param gr A graphic as a Graphics type

23 */

50 gr.setColor(Color.lightGray);

51 gr.fillRect(70,180,30, height - 180);

52 gr.setColor(Color.magenta);

53 gr.fillRect(100,110,50,height - 110);

gr.setColor(Color.lightGray);

55 gr.fillRect(150,150,100, height - 150);

56 gr.setColor(Color.magenta);

57 gr.fillRect(200,100,40, height - 100);

58 }

59 }

60

61 /**

62 * @param e An event as an ActionEvent data type

63 */

public void paint(Graphics gr) elseelse

76 ++x;

77 }

78 } // end class

Applets

What are applets?

The early popularity of the Java language is attributed to Java applets. An applet is a small program or application that is run within a Web browser such as Netscape Navigator or Microsoft Internet Explorer.

The popularity of Java applets was in large part due to the widespread use of the World Wide Web. The WWW network has made information accessible through documents that use HTML. HTML documents can be either static, which provides static information, or dynamic, which includes interactive graphics and content presentations. One such user-interactive technology that can be embedded in a HTML document is the Java applet.

The Java programming language allows developers to create powerful software tools. These tools can either run standalone, inside the Java virtual machine, or they can run inside other programs. A Java program that runs standalone is called a Java application. An applet is a Java program that requires a Web browser to run it. Web browsers are programs that are used to display Web pages from other computers. These computers are connected to the network of computers on the Internet, known as the World Wide Web. It is possible to embed a Java applet within one of these Web pages, so that when a user views the Web page, the embedded Java applet starts automatically. In this manner, Java programs can also be a resource that is available to the Internet users. Applets are the Java technologies that make this happen.

Traditionally, the word applet has come to mean any small application. A Java applet is any program that is launched from a Web page, or an HTML file. Java applications are programs that run from the command line, independent of a Web browser. A Java applet has no limit in size or in complexity. On the Internet, applets are often designed to be small by necessity.

Applets represent container objects. These containers can display the graphics and other GUI components in a frame.

Class hierarchies

The Applet class is part of the Component subclasses and it inherits from the Panel class. Recall that the Panel is a free-floating container and cannot be displayed alone. The Panel is usually displayed in a Frame or a Window. Since an applet is a Panel, it needs to be displayed in a Container that can render its graphical components. The Web browser window serves as this container. The Applet is a Panel subclassed from the Panel class that inherits the default layout manager FlowLayout from the Panel class. All components will be added from left to right. The FlowLayout manager maintains the size of the component. Components are not changed when the user resizes the Panel or Frame.

The applet inherits methods from the Component, Container, and Panel classes. Figures 1 and 2 show the inheritance of the Applet class.

Launching applets

In all of the classes so far, the main method is the starting point of the program. The Java interpreter begins the application by locating the main method in the class that is passed as a parameter to the JVM and then runs the code in this method. Running an applet is more complex than running an application. Simply typing in a command cannot run an applet.

The basic steps in the creation and use of applets are outlined here:



Design the GUI that should be displayed.

Create a class that extends from the Applet class.

Compile the applet.

Create an HTML file and insert the statements that pass the name of an applet, a class derived from Applet, to a browser.

Open a browser or use the appletviewer program and call the HTML file.

Review the code shown in Figure 1. This Java class is an Applet. This simple applet, TodayIS, provides a button and displays a message.

2 * TodayIS.java

3 * @author Cisco Teacher

4 * @version 2002

5 */

6

7 import java.applet.*;

8 import java.awt.*;

9 import java.awt.event.*;

10 import java.util.*;

11

12 public class TodayIS extends Applet implements ActionListener

25

26 /**

27 * @param e An event as an ActionEvent data type

28 */

29 public void actionPerformed(ActionEvent e)

38 }// end class

The launching of an applet goes through the steps described in Figure 2.

Figure 3 animates two different ways to launch Lights.java, which is the applet shown in Figure 4.

Begin by loading a browser, and point the browser to a URL, which is a specific address for an HTML document. The URL could be either a reference to a directory on the machine or an Internet address for another machine.

A browser accesses the URL and locates the HTML document. Then, it loads the HTML document and interprets it. Then, it locates the Applet classes referenced by the HTML document, loads them, and runs them.

A Java applet differs from the Java stand-alone programs that have been created so far. An applet cannot be run directly. It requires an HTML file and a browser to display the HTML file. The sample code presented in the figure represents the .java file and the HTML file. The format of the HTML file is described in the next sections.

The differences between an applet and an application stem from the context in which they run. A Java application runs in the simplest of environments. Its only input from the outside world is a list of command line parameters. A Java applet receives a lot of information from a Web browser. It needs to know when it is initialized, where to draw itself in the browser window, and when it is activated and deactivated. User movement from one page of the browser to another needs to be communicated to the applet.

The table in Figure 5 shows a comparison between a Java application and a Java applet.

The Java development environment also provides the appletviewer program to test run the applets. Figure 6 shows that an applet can be launched from the command line with the appletviewer.

A Java application runs in the simplest of environments. Its only input from the outside world is a list of command line parameters. A Java applet receives a lot of information from the Web browser. One feature of an applet is that data, or parameters from the browser can be sent to the applet. This concept is used extensively in Java Server Pages (JSP) and servlet technologies. In an applet the following command extracts data from the browser, through the parameters defined in the HTML document:

String s = getParameter('p')

The getParameter method of the Applet class accepts a String. This String represents the variable name of the parameter that will be passed by the browser. This variable is declared in the HTML document as shown in Figure 7.

Messages can also be sent from an applet to a browser for display in the browser message area. The showStatus() method of the applet is used to display a message in the browser status area as shown in Figure 8. 

Applets and security

When a user downloads an applet in their browser, the applet runs in the memory of the user's computer. A browser launches a copy of the JVM to run these applets. As such, the code of the applet is inherently dangerous because the applet is loaded over a network and resides in the client memory. There are several security concerns. What if a class that is downloaded writes to the hard drive with the same file name as one of the documents? What if a person creates a malicious class that reads personal files and sends them out over the Internet? What if the applet is coded to erase important files on a computer? What if the Applet class name is the same as some other class that is running?

The threat of malicious damage to computers and networks has resulted in most browsers implementing security measures against code that is downloaded from another machine. The depth of security is implemented at the browser level. Most browsers prevent several actions by default. The figure shows the security actions prevented by default for applets accessed over the Internet. An applet loaded from the local file system has more privileges. A remotely-loaded applet that attempts to perform any of these actions will cause exceptions to be thrown and the applet will fail to load.

Embedding a Java applet

The HTML language has many features and commands for presenting content. A comprehensive coverage of the HTML language requires a separate study. The use of special tags to create HTML files when documenting classes has already been seen. The javadoc utility takes the comment tags and converts them to HTML tags, which can be displayed by a browser. In a similar manner, a document will be created and HTML tags will be inserted to set the size of the applet to be displayed, the specific applet class to run, and a few other parameters.

HTML commands are used to format text for display as a Web page, import graphics and images, and link a page to other Web pages. HTML commands are also known as tags. Tags are special keywords enclosed in < > symbols. A tag includes a keyword that starts the markup command and ends the markup command. To run a Java applet, only two tags must be learned by a programmer. These are HTML and APPLET.

An HTML document always begins with a tag that identifies the HTML block of content. This is the <HTML> tag. The document ends with the </HTML> closing tag.

To embed applets in an HTML document, the two sets of tags that are used are <HTML> </HTML> and <APPLET> </APPLET>. Place the attributes CODE, WIDTH, and HEIGHT inside of the applet tag. CODE is the attribute that points to the name of the Java class file. WIDTH is the width of the applet on the screen. HEIGHT is the height of the applet on the screen.

The height and width of the applet are measured in pixels. Pixels, or picture elements, are the number of lighted dots that are required to display an image. Most common monitors display 640 pixels horizontally and 480 pixels vertically. A statement such as WIDTH = 300 and HEIGHT = 200 would be approximately half the size of a screen. Many monitors can display higher resolution, or pixels per inch. It is recommended to keep the applet size within the 640X480 pixels resolution. Keep in mind that browsers display titles, menus, and messages. The applet should be easily viewed alongside these other objects, which should be accessible to the user.

Generally an applet should be less than 800 pixels wide and 600 pixels tall. Most computers support these dimensions.

Additional characters such as commas (,) between the attributes in the <APPLET> tag may cause an appletviewer or browser to produce a MissingResourceException when loading the applet.

Forgetting the ending </APPLET> tag prevents an applet from loading into an appletviewer or browser properly.

The MissingResourceException can be addressed by checking the <APPLET> tag in the HTML file carefully for syntax errors.

Running the appletviewer with a file name that does not end with .html or .htm is an error that will prevent an applet from loading.

Note: Make sure that the class file is compiled before running the HTML document.

Creating an applet

To create an applet, start by creating a class using the form displayed in the figure. The class of the applet must be public, and its name must match its filename. In this case, the file is named HelloWorld.java. The class must be derived from the class Applet that is in the java.applet package.

Writing an Applet class will require several things:

  • Adding more import statements such as java.awt.*or java.awt.event.*
  • Adding components
  • Implementing the methods to handle what happens to an applet when resized or minimized
  • Including the use of the Font and Color classes to set the properties of text and graphics
  • Including the use of the Graphics class to draw images on the display
  • Implementing event handling through the event delegation model, which involves using WindowListener and ActionListener objects to handle events

In this sample, the Applet class is imported from the java.applet package with the use of an import statement. The class definition statement uses the keyword extends to show that this class is an applet.

Applet inherited methods

The Applet class inherits methods from the Component, Container, and Panel classes. The figure displays the inherited methods. In addition to these, the Applet class has its own methods for initializing an applet and closing or destroying the applet object. Applets have add methods to add components, set methods to set values and properties of components, get methods to retrieve values of components, and addXXXListener and removeXXXListener methods to implement event handling. Like all Component objects, an applet includes methods to paint, repaint, and update its Graphics.

An applet is a Container, so it can contain numerous Panels with different layout managers. Other components such as Labels, Buttons, TextFields, and Scrollbars, can be added to these Panels or to the applet directly. In addition to methods for adding components, the set methods can be used to set the properties of the components such as color, font, and size. The listener objects can be registered with the components that will generate event objects using the addXXXListener methods. 'XXX' stands for the name of the listener for the event generated by the component. The steps to create the GUI features of an applet are the same as the steps used to create stand-alone applications that present GUIs.

The Applet class inherits methods from the Component and the Container class. In addition to these, the Applet class has its own methods for initializing an Applet and closing or destroying the applets object.

Applet life cycle methods

When an applet is launched, the graphics that form the applet have to be painted on the screen for the first time. When the applet window is resized or minimized, the graphics have to be redrawn. When a user moves from the current document to a different HTML document and then returns back to the HTML with the applet, the applet needs to be painted.

The lifecycle methods of the applet are listed in Figure 1.

The Applet class provides a general outline to be used by any browser when it runs an applet. In an application, the main() method calls other methods. With an applet, the browser calls many methods automatically. Every applet includes the four methods shown in this figure. If code is not written for one of these methods, the compiler creates it automatically. The methods that the compiler creates do not do anything special. They are created with empty braces. The first method the browser calls is the init() method. This is the method in which code must be written to create the components. Other key methods are called depending on the actions being performed. A simple flow of the lifecycle methods is shown in Figure 2.

When the window is closed, the destroy() method is called. In this method, the program should initiate actions to release resources, close input/output streams, and any network connections. The stop() and destroy() methods do not have to be written. Any tasks that must be performed when the applet is no longer visible can be defined in the stop() and destroy() methods of the applet.

The only statements that should be placed in an init() method of an applet are those that are related directly to the one-time initialization of the component instance variables of the applet. Results that involve drawing should be displayed from the paint method of the applet.

The statements to be placed in the paint method should be related directly to drawing, calls to methods of the Graphics object, and the logic of drawing. Dialog boxes should not be displayed from the paint() method of an applet. The paint method should do as little computation as possible.

Every applet must subclass Applet, as shown for the AnyApplet class in Figure 3.

1 import java.applet.*;

2 import java.awt.*;

3 public class AnyApplet extends Applet

6 public void start()

8 public void stop()

10 public void destroyed()

12 public void paint(Graphics g)

14 // other handler methods can be defined here, or utility methods, and or inner classes.

15 } // end of applet class definition

16 //This is the applet's accompanying HTML file

GUI Components in Applets

GUI components

The Applet class extends from Panel, which extends from Container. An Applet is a Container. Any AWT component can be added to the applet. Code can also be included to set the font and color of some components. Graphic objects can be included using the Graphics class to draw simple shapes or combine simple shapes to create complex images. Some simple uses of Graphics objects are described later in this module.

The code in Figure 1 demonstrates the use of Label, TextField, and Button objects in an applet. This program presents the user with TextFields to enter a username and password. The username and password are checked against a list. The applet returns a message if the entry is correct. The actual verification of user names and passwords in a business application can be far more complex than this example. Often this will include retrieving data from a database to verify that the information is correct. Here, it can be assumed that only a single password, rosetime, is acceptable to the program.

1 import java.applet.*;

2 import java.awt.*;

3 import java.awt.event.*;

4

5 public class PasswordTest extends Applet implements ActionListener

25 public void actionPerformed(ActionEvent e)

43 }

Samples of output from the program are shown in Figure 2. The class definition includes references to import classes from three sources. These are java.applet.* to use the Applet class, java.awt.* to use the Component class and its subclasses, and java.awt.event.* to use Listener interfaces and event objects. This applet implements event handling code, so that interaction with the applet produces certain results.

These concepts are demonstrated by the following code:

  • Components are added in the init() method. The init() method will be followed by the start() method, which calls the paint() method to draw the graphics for each component.
  • The PasswordTest object referenced by the keyword this implements event handling code. When a user presses the button on the applet screen, an action will occur.
  • The focus is requested for the object referenced by un.requestFocus();.
  • The actionPerformed method is implementation to provide event handling and user response technologies. In the actionPerformed method, the code verifies the data provided by the user, changes the text for the Label object referenced by result, and adds a label component to the applet.
  • Since components of the applet have changed, the invalidate() method is called to mark the applet as invalid or out-of-date and a call to the validate() method is given to redraw the window and implement the addition of the new label referenced by result.

Other applet methods

In addition to the key methods, the graphics of the applet are painted and repainted as shown in the table in Figure 1.

When adding components to an applet, additional methods must be implemented. The init() method lays out all the components of the applet. The init() method is called once when the applet loads. If the applet code adds or removes components, two methods must be called to have the applet redraw the components. These are the invalidate() and validate() methods. When moving out of a window, or resizing the window, the applet knows that the window needs to be redrawn. It will redraw based on the original information about the components. When a component is added, the applet does not know that its information is out-of-date. A programmer needs to call the invalidate() method for the applet. This marks it as out of date. The validate() method then redraws any invalid windows, allowing the changes to take effect. This is shown in Figure 2.

1 // TodayIS.java

2 import java.applet.*;

3 import java.awt.*;

4 import java.awt.event.*;

5 import java.util.*;

6

7 public class TodayIS extends Applet implements ActionListener

1 public void actionPerformed(ActionEvent e)

31 }

The FlowLayout manager manages the placement of the components on an applet. Since an applet is a Panel, this is the default layout manager for all Panels and their subclasses. The FlowLayout manager places the components from left to right and top to bottom once each row is filled.

If the layout manager is turned off, control can be exercised over the placement of components using the setLocation() method, inherited from the java.awt.Component class. The applet window consists of horizontal and vertical pixels on the screen. Each component has several location and size values. The upper left corner of the applet display area has the value of 0,0. These two numbers represent the horizontal position or the x-axis and the vertical position or the y-axis. Just as the top left corner of the display is set to 0,0 for both the x and y axis, each component is placed within this display and its location can be described as some value from the 0,0 position of the display. This is shown in Figures 3 and 4.

The public void setLocation(int x, int y) method provides a way to control the position of the components in the applet display area. The method arguments include an integer to define the x value and another integer to define the y value. This is shown in Figure 5.

Components can also be made available or unavailable and visible or hidden. The method setEnabled() will make a component available if a boolean true is supplied to the method, and unavailable if the boolean false is supplied to the method. When a component is unavailable it is still visible, but the user cannot interact with it.

The method setVisible() was introduced in the previous module to make all the components of a Frame visible. This method can also be used on components of an applet to make them visible or hidden. This is shown in Figure 6.

1 import java.applet.*;

2 import java.awt.*;

3 import java.awt.event.*;

4

5 public class HideAndSeek extends Applet implements ActionListener

22 public void actionPerformed(ActionEvent e)

28

29 if (e.getSource() == stop )

33

34 if (e.getSource() == hide )

35

Paint and repaint graphics

In addition to the basic lifecycle methods, an applet has other important methods related to its display. These methods are declared and documented for the AWT Component class. Exposure handling occurs automatically and results in a call to the paint() method. A facility of the graphics class, called a clip rectangle, optimizes the paint() method. The painting and repainting of images is performed by the paint(), update(), and repaint() methods.

Displaying the graphics on the screen is also known as exposure. This figure illustrates what occurs. The paint() method is called by the start() method. This is the first exposure of the graphics. The graphics will be redrawn if the window loses focus, that is, if the user has moved to another window or minimized it. For these conditions, the start() method is called, which then calls the paint() method. The second exposure happens if the programmer wants to make changes to the display. The area that is changed is considered a damaged area. That is, it is now different from when the area was first painted. The program must be able to update the display at any time. When the display is updated, the old image may first need to be removed.

The methods that draw the images or handle image painting are described next:

paint() — Updates are not made over the entire area of the graphics unless necessary. Rather, these updates are restricted to the region that has been damaged or changed. Override the paint() method to control what is painted on the applet. In the Skylined example, the paint() method is used to change the colors of the rectangles, the oval, and the background for the graphics. The signature for this method is paint(Graphics g).

  • repaint() — A call to the repaint() method notifies the system that the programmer wants to change the display. These methods do not repaint the entire graphics, only the part that has been changed. 
  • update() — The repaint() method causes a call to the update() method of the component as soon as possible. The update() method usually clears the current display and calls paint(). The update() method can be modified, for example, to reduce flicker by calling paint() without clearing the display.





Politica de confidentialitate



DISTRIBUIE DOCUMENTUL

Comentarii


Vizualizari: 648
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2021 . All rights reserved

Distribuie URL

Adauga cod HTML in site