COP 4610 L Applications in the Enterprise Fall

  • Slides: 59
Download presentation
COP 4610 L: Applications in the Enterprise Fall 2006 GUI Components: Part 2 Instructor

COP 4610 L: Applications in the Enterprise Fall 2006 GUI Components: Part 2 Instructor : Mark Llewellyn markl@cs. ucf. edu CSB 242, 823 -2790 http: //www. cs. ucf. edu/courses/cop 4610/fall 2006 School of Computer Science University of Central Florida COP 4610 L: GUI Components Part 2 Page 1 Mark Llewellyn ©

Mouse Event Handling • The Mouse. Listener and the Mouse. Motion. Listener event-listener interfaces

Mouse Event Handling • The Mouse. Listener and the Mouse. Motion. Listener event-listener interfaces are designed to handle mouse events. Mouse events can be trapped for any GUI component that derives from java. awt. Component. • Package javax. swing. event contains interface Mouse. Input. Listener, which extends the two interfaces to create a single interface which contains all the methods of both interfaces. • The Mouse. Listener and the Mouse. Motion. Listener methods are called with the mouse interacts with a Component if the appropriate event-listener objects are registered for that Component. COP 4610 L: GUI Components Part 2 Page 2 Mark Llewellyn ©

Mouse Event Handling (cont. ) • Each of the mouse event-handling methods takes a

Mouse Event Handling (cont. ) • Each of the mouse event-handling methods takes a Mouse. Event object as its argument. A Mouse. Event object contains information about the mouse event that occurred, including the x- and y-coordinates of the location where the event occurred. • These coordinates are measured form the upper-left corner of the GUI component on which the event occurred. • – The x-coordinates begin a 0 and increase from left to right. – The y-coordinates begin an 0 and increase from top to bottom. In addition, the methods and constants of class Input. Event (Mouse. Event’s superclass) enable an application to determine which mouse button was clicked. COP 4610 L: GUI Components Part 2 Page 3 Mark Llewellyn ©

Mouse. Listener and Mouse. Motion. Listener Interface Methods of Interface Mouse. Listener public void

Mouse. Listener and Mouse. Motion. Listener Interface Methods of Interface Mouse. Listener public void mouse. Pressed(Mouse. Event event) called when a mouse button is pressed while the mouse cursor is on a component. public void mouse. Clicked(Mouse. Event event) called when a mouse button is pressed and released while the mouse cursor remains stationary on a component. This event is always preceded by a call to mouse. Pressed. public void mouse. Released(Mouse. Event event)called when a mouse button is released after being pressed. This event is always preceded by a call to mouse. Pressed and one or more calls to mouse. Dragged. public void mouse. Enetered(Mouse. Event event) called when the mouse cursor enters the bounds of a component. public void mouse. Exited(Mouse. Event event)called when the mouse cursor leaves the bounds of a component. COP 4610 L: GUI Components Part 2 Page 4 Mark Llewellyn ©

Mouse. Listener and Mouse. Motion. Listener Interface Methods of Interface Mouse. Motion. Listener public

Mouse. Listener and Mouse. Motion. Listener Interface Methods of Interface Mouse. Motion. Listener public void mouse. Dragged(Mouse. Event event) called when the mouse button is pressed while the mouse cursor is on a component and the mouse is moved while the mouse button remains pressed. This event is always preceded by a call to mouse. Pressed. All drag events are sent to the component on which the user began to drag the mouse. public void mouse. Moved(Mouse. Event event) called when the mouse is moved when the mouse cursor is on a component. All move events are sent to the component over which the mouse is currently positioned. Java also provides interface Mouse. Wheel. Listener to enable applications to respond to the rotation of a mouse wheel. This interface declares method mouse. Wheel. Moved, which receives a Mouse. Wheel. Event as its argument. Class Mouse. Wheel. Event (a subclass of Mouse. Event) contains methods that enable the event handler to obtain information about the amount of wheel rotation. COP 4610 L: GUI Components Part 2 Page 5 Mark Llewellyn ©

// Demonstrating mouse events. GUI Example illustrating import java. awt. Color; import java. awt.

// Demonstrating mouse events. GUI Example illustrating import java. awt. Color; import java. awt. Border. Layout; Mouse Events import java. awt. event. Mouse. Listener; import java. awt. event. Mouse. Motion. Listener; import java. awt. event. Mouse. Event; import javax. swing. JFrame; import javax. swing. JLabel; import javax. swing. JPanel; public class Mouse. Tracker. Frame extends JFrame { private JPanel mouse. Panel; // panel in which mouse events will occur private JLabel status. Bar; // label that displays event information // Mouse. Tracker. Frame constructor sets up GUI and registers mouse event handlers public Mouse. Tracker. Frame() { super( "Demonstrating Mouse Events" ); mouse. Panel = new JPanel(); // create panel mouse. Panel. set. Background( Color. WHITE ); // set background color add( mouse. Panel, Border. Layout. CENTER ); // add panel to JFrame status. Bar = new JLabel( "Mouse outside JPanel" ); add( status. Bar, Border. Layout. SOUTH ); // add label to JFrame // create and register listener for mouse and mouse motion events Mouse. Handler handler = new Mouse. Handler(); mouse. Panel. add. Mouse. Listener( handler ); mouse. Panel. add. Mouse. Motion. Listener( handler ); } // end Mouse. Tracker. Frame constructor COP 4610 L: GUI Components Part 2 Page 6 Mark Llewellyn ©

private class Mouse. Handler implements Mouse. Listener, Mouse. Motion. Listener { // Mouse. Listener

private class Mouse. Handler implements Mouse. Listener, Mouse. Motion. Listener { // Mouse. Listener event handlers handle event when mouse released immediately // after press public void mouse. Clicked( Mouse. Event event ) { status. Bar. set. Text( String. format( "Clicked at [%d, %d]", event. get. X(), event. get. Y() ) ); } // end method mouse. Clicked // handle event when mouse pressed public void mouse. Pressed( Mouse. Event event ) { status. Bar. set. Text( String. format( "Pressed at [%d, %d]", event. get. X(), event. get. Y() ) ); } // end method mouse. Pressed // handle event when mouse released after dragging public void mouse. Released( Mouse. Event event ) { status. Bar. set. Text( String. format( "Released at [%d, %d]", event. get. X(), event. get. Y() ) ); } // end method mouse. Released COP 4610 L: GUI Components Part 2 Page 7 Mark Llewellyn ©

// handle event when mouse enters area public void mouse. Entered( Mouse. Event event

// handle event when mouse enters area public void mouse. Entered( Mouse. Event event ) { status. Bar. set. Text( String. format( "Mouse entered at [%d, %d]", event. get. X(), event. get. Y() ) ); mouse. Panel. set. Background( Color. GREEN ); } // end method mouse. Entered // handle event when mouse exits area public void mouse. Exited( Mouse. Event event ) { status. Bar. set. Text( "Mouse outside JPanel" ); mouse. Panel. set. Background( Color. WHITE ); } // end method mouse. Exited // Mouse. Motion. Listener event handlers handle event when user drags mouse with // button pressed public void mouse. Dragged( Mouse. Event event ) { status. Bar. set. Text( String. format( "Dragged at [%d, %d]", event. get. X(), event. get. Y() ) ); } // end method mouse. Dragged // handle event when user moves mouse public void mouse. Moved( Mouse. Event event ) { status. Bar. set. Text( String. format( "Mouse located at [%d, %d]", event. get. X(), event. get. Y() ) ); } // end method mouse. Moved } // end inner class Mouse. Handler } // end class Mouse. Tracker. Frame COP 4610 L: GUI Components Part 2 Page 8 Mark Llewellyn ©

Some sample screen shots showing capture of mouse motion COP 4610 L: GUI Components

Some sample screen shots showing capture of mouse motion COP 4610 L: GUI Components Part 2 Page 9 Mark Llewellyn ©

Adapter Classes • Many event-listener interfaces, such as Mouse. Listener and Mouse. Motion. Listener,

Adapter Classes • Many event-listener interfaces, such as Mouse. Listener and Mouse. Motion. Listener, contain multiple methods. It is not always a good thing to declare every methods in an event-listener interface. – For example, an application may need only the mouse. Clicked handler from Mouse. Listener or the mouse. Dragged handler from Mouse. Motion. Listener. Interface Window. Listener specifies seven window event-handling methods. • For many of the listener interfaces that have multiple methods, packages java. awt. event and javax. swing. event provide event-listener adapter classes. • An adapter class implements an interface and provides a default implementation (with an empty method body) of each method in the interface. You can extend an adapter class to inherit the default implementation of every method and subsequently override only the method(s) that you need for event handling. COP 4610 L: GUI Components Part 2 Page 10 Mark Llewellyn ©

Event-Adapter Classes in java. awt. event Event-adapter class in java. awt. event Implements interface

Event-Adapter Classes in java. awt. event Event-adapter class in java. awt. event Implements interface Component. Adapter Component. Listener Container. Adapter Container. Listener Focus. Adapter Focus. Listener Key. Adapter Key. Listener Mouse. Adapter Mouse. Listener Mouse. Motion. Adapter Mouse. Motion. Listener Window. Adapter Window. Listener COP 4610 L: GUI Components Part 2 Page 11 Mark Llewellyn ©

GUI Example illustrating Adapter Class for Mouse Events // Demonstrating mouse clicks and distinguishing

GUI Example illustrating Adapter Class for Mouse Events // Demonstrating mouse clicks and distinguishing between mouse buttons. import java. awt. Border. Layout; import java. awt. Graphics; import java. awt. event. Mouse. Adapter; import java. awt. event. Mouse. Event; import javax. swing. JFrame; import javax. swing. JLabel; public class Mouse. Details. Frame extends JFrame { private String details; // String representing movement private JLabel status. Bar; // JLabel that appears at bottom of window // constructor sets title bar String and register mouse listener public Mouse. Details. Frame() { super( "Mouse clicks and buttons" ); status. Bar = new JLabel( "Click the mouse" ); add( status. Bar, Border. Layout. SOUTH ); add. Mouse. Listener( new Mouse. Click. Handler() ); // add handler } // end Mouse. Details. Frame constructor COP 4610 L: GUI Components Part 2 Page 12 Mark Llewellyn ©

// inner class to handle mouse events private class Mouse. Click. Handler extends Mouse.

// inner class to handle mouse events private class Mouse. Click. Handler extends Mouse. Adapter { // handle mouse click event and determine which button was pressed public void mouse. Clicked( Mouse. Event event ) { int x. Pos = event. get. X(); // get x position of mouse int y. Pos = event. get. Y(); // get y position of mouse details = String. format( "Clicked %d time(s)", event. get. Click. Count() ); if ( event. is. Meta. Down() ) // right mouse button details += " with right mouse button"; else if ( event. is. Alt. Down() ) // middle mouse button details += " with center mouse button"; else // left mouse button details += " with left mouse button"; status. Bar. set. Text( details ); // display message in status. Bar } // end method mouse. Clicked } // end private inner class Mouse. Click. Handler } // end class Mouse. Details. Frame COP 4610 L: GUI Components Part 2 Page 13 Mark Llewellyn ©

JText. Area • A JText. Area provides an area for manipulating multiple lines of

JText. Area • A JText. Area provides an area for manipulating multiple lines of text. Like class JText. Field, JText. Area is a subclass of JText. Component. • Recall that JText. Component declares common methods for JText. Fields, JText. Areas, and several other text-based GUI components. • The next example illustrates the use of a JText. Area and is similar in nature to the previous example involving multiple selection lists. • Note that by default, a JText. Area does not automatically wrap lines. To turn line wrapping on for a JText. Area invoke JText. Area method set. Line. Wrap with a true argument. COP 4610 L: GUI Components Part 2 Page 14 Mark Llewellyn ©

// Example of JText. Area - Copying selected text from one // textarea to

// Example of JText. Area - Copying selected text from one // textarea to another. import java. awt. event. Action. Listener; import java. awt. event. Action. Event; import javax. swing. Box; import javax. swing. JFrame; import javax. swing. JText. Area; import javax. swing. JButton; import javax. swing. JScroll. Pane; GUI Example illustrating JText. Area Class public class Text. Area. Frame extends JFrame { private JText. Area text. Area 1; // displays demo string private JText. Area text. Area 2; // highlighted text is copied here private JButton copy. JButton; // initiates copying of text // no-argument constructor public Text. Area. Frame() { super( "Text. Area Demo" ); Box box = Box. create. Horizontal. Box(); // create box String demo = "This is a demo string ton" + "illustrate copying textnfrom one textarea to n" + "another textarea using annexternal eventn"; text. Area 1 = new JText. Area( demo, 10, 15 ); // create textarea 1 box. add( new JScroll. Pane( text. Area 1 ) ); // add scrollpane copy. JButton = new JButton( "Copy >>>" ); // create copy button COP 4610 L: GUI Components Part 2 Page 15 Mark Llewellyn ©

box. add( copy. JButton ); // add copy button to box copy. JButton. add.

box. add( copy. JButton ); // add copy button to box copy. JButton. add. Action. Listener( new Action. Listener() // anonymous inner class { // set text in text. Area 2 to selected text from text. Area 1 public void action. Performed( Action. Event event ) { text. Area 2. set. Text( text. Area 1. get. Selected. Text() ); } // end method action. Performed } // end anonymous inner class ); // end call to add. Action. Listener text. Area 2 = new JText. Area( 10, 15 ); // create second textarea text. Area 2. set. Editable( false ); // disable editing box. add( new JScroll. Pane( text. Area 2 ) ); // add scrollpane add( box ); // add box to frame } // end Text. Area. Frame constructor } // end class Text. Area. Frame COP 4610 L: GUI Components Part 2 Page 16 Mark Llewellyn ©

Initial GUI User selects text to be copied. Clicking “COPY” button copies text to

Initial GUI User selects text to be copied. Clicking “COPY” button copies text to second JText. Area COP 4610 L: GUI Components Part 2 Page 17 Mark Llewellyn ©

Another Layout Manager: Border. Layout • The Border. Layout manager, which is the default

Another Layout Manager: Border. Layout • The Border. Layout manager, which is the default layout manager for JFrame windows, arranges components into five regions: NORTH, SOUTH, EAST, WEST, and CENTER. • NORTH corresponds to the top of the container. • A Border. Layout limits a container to containing at most 5 components – one in each region. However, the component in each region can be a container to which other components are attached. • The EAST and WEST regions expand vertically between the NORTH and SOUTH regions and are as wide as the components placed in those regions. • The example on the next page illustrates the Border. Layout manager. COP 4610 L: GUI Components Part 2 Page 18 Mark Llewellyn ©

// Demonstrating Border. Layout. import java. awt. Border. Layout; import java. awt. event. Action.

// Demonstrating Border. Layout. import java. awt. Border. Layout; import java. awt. event. Action. Listener; import java. awt. event. Action. Event; import javax. swing. JFrame; import javax. swing. JButton; public class Border. Layout. Frame extends JFrame implements Action. Listener { private JButton buttons[]; // array of buttons to hide portions private final String names[] = { "Hide North", "Hide South", "Hide East", "Hide West", "Hide Center" }; private Border. Layout layout; // borderlayout object // set up GUI and event handling public Border. Layout. Frame() { super( "Border. Layout Demo" ); layout = new Border. Layout( 5, 5 ); // 5 pixel gaps set. Layout( layout ); // set frame layout buttons = new JButton[ names. length ]; // set size of array // create JButtons and register listeners for them for ( int count = 0; count < names. length; count++ ) { buttons[ count ] = new JButton( names[ count ] ); buttons[ count ]. add. Action. Listener( this ); } // end for COP 4610 L: GUI Components Part 2 Page 19 GUI Example illustrating Border. Layout Manager Mark Llewellyn ©

add( buttons[ 0 ], Border. Layout. NORTH ); // add button to north add(

add( buttons[ 0 ], Border. Layout. NORTH ); // add button to north add( buttons[ 1 ], Border. Layout. SOUTH ); // add button to south add( buttons[ 2 ], Border. Layout. EAST ); // add button to east add( buttons[ 3 ], Border. Layout. WEST ); // add button to west add( buttons[ 4 ], Border. Layout. CENTER ); // add button to center } // end Border. Layout. Frame constructor // handle button events public void action. Performed( Action. Event event ) { // check event source and layout content pane correspondingly for ( JButton button : buttons ) { if ( event. get. Source() == button ) button. set. Visible( false ); // hide button clicked else button. set. Visible( true ); // show other buttons } // end for layout. Container( get. Content. Pane() ); // layout content pane } // end method action. Performed } // end class Border. Layout. Frame COP 4610 L: GUI Components Part 2 Page 20 Mark Llewellyn ©

Initial GUI after clicking on “Hide West” button GUI after clicking on “Hide South”

Initial GUI after clicking on “Hide West” button GUI after clicking on “Hide South” button COP 4610 L: GUI Components Part 2 Page 21 Mark Llewellyn ©

Advanced GUIs • In the notes up to this point, we have examined a

Advanced GUIs • In the notes up to this point, we have examined a number of different capabilities for GUI programming that are available in Java. Most of the examples have simply illustrated the some of the options which are available for designing and manipulating GUIs. • At this point, we’ll begin to look at more sophisticated applications for the GUIs which are more along the lines of what you will be programming in this course. • As before, many of the examples in the notes will simply illustrate one option from many that are available. I encourage you to look at the Java documentation and experiment either by modifying the code from the notes or constructing your own GUIs using some of these additional options. COP 4610 L: GUI Components Part 2 Page 22 Mark Llewellyn ©

File Choosers • File choosers provide a GUI for navigating the file system and

File Choosers • File choosers provide a GUI for navigating the file system and then selecting a file or directory from a list (or by directly entering the name of a file or directory). • The JFile. Chooser API makes it easy to bring up open and save dialogs. The look and feel determines what the standard dialogs look like and how they differ. • In the Java look and feel, the save dialog looks the same as the open dialog except for the title on the dialog’s window and the text on the button that approves the operation. • The next slide illustrates the Java look and feel’s standard open dialog. COP 4610 L: GUI Components Part 2 Page 23 Mark Llewellyn ©

Standard Java Look and Feel Open File Dialog COP 4610 L: GUI Components Part

Standard Java Look and Feel Open File Dialog COP 4610 L: GUI Components Part 2 Page 24 Mark Llewellyn ©

File Chooser Demo • The code on the following page demonstrates some of the

File Chooser Demo • The code on the following page demonstrates some of the features of the JFile. Chooser open and save dialogs. • Try some of the options which are listed in the comments in the code. COP 4610 L: GUI Components Part 2 Page 25 Mark Llewellyn ©

import java. io. *; import java. awt. event. *; import javax. swing. filechooser. *;

import java. io. *; import java. awt. event. *; import javax. swing. filechooser. *; File. Chooser. Demo /* * File. Chooser. Demo. java is a 1. 5. 0 application that uses these files: * images/Open 16. gif * images/Save 16. gif */ public class File. Chooser. Demo extends JPanel implements Action. Listener { static private final String newline = "n"; JButton open. Button, save. Button; JText. Area log; JFile. Chooser fc; public File. Chooser. Demo() { super(new Border. Layout()); //Create the log first, because the action listeners need to refer to it. log = new JText. Area(5, 20); log. set. Margin(new Insets(5, 5, 5, 5)); log. set. Editable(false); JScroll. Pane log. Scroll. Pane = new JScroll. Pane(log); COP 4610 L: GUI Components Part 2 Page 26 Mark Llewellyn ©

//Create a file chooser fc = new JFile. Chooser(". "); //this constructor allows you

//Create a file chooser fc = new JFile. Chooser(". "); //this constructor allows you to specify the directory to be opened // ". " is the current default directory, ". . " would be the parent of the //default or current directory. //Uncomment one of the following lines to try a different Change the argument to the //file selection mode. The first allows just directories file chooser constructor to set //to be selected (and, at least in the Java look and feel, the default directory which is //shown). The second allows both files and directories opened. //to be selected. If you leave these lines commented out, //then the default mode (FILES_ONLY) will be used. // //fc. set. File. Selection. Mode(JFile. Chooser. DIRECTORIES_ONLY); Uncomment these //fc. set. File. Selection. Mode(JFile. Chooser. FILES_AND_DIRECTORIES); lines to change the file selection mode. //Create the open button. We use the image from the JLF //Graphics Repository (but we extracted it from the jar). open. Button = new JButton("Open a File. . . ", create. Image. Icon("images/Open 16. gif")); open. Button. add. Action. Listener(this); // Create the save button. We use the image from the JLF // Graphics Repository (but we extracted it from the jar). save. Button = new JButton("Save a File. . . ", create. Image. Icon("images/Save 16. gif")); save. Button. add. Action. Listener(this); // For layout purposes, put the buttons in a separate panel JPanel button. Panel = new JPanel(); //use Flow. Layout button. Panel. add(open. Button); button. Panel. add(save. Button); COP 4610 L: GUI Components Part 2 Page 27 Mark Llewellyn ©

//Add the buttons and the log to this panel. add(button. Panel, Border. Layout. PAGE_START);

//Add the buttons and the log to this panel. add(button. Panel, Border. Layout. PAGE_START); add(log. Scroll. Pane, Border. Layout. CENTER); } public void action. Performed(Action. Event e) { //Handle open button action. if (e. get. Source() == open. Button) { int return. Val = fc. show. Open. Dialog(File. Chooser. Demo. this); if (return. Val == JFile. Chooser. APPROVE_OPTION) { File file = fc. get. Selected. File(); //This is where a real application would open the file. log. append("Opening: " + file. get. Name() + ". " + newline); } else { log. append("Open command cancelled by user. " + newline); } log. set. Caret. Position(log. get. Document(). get. Length()); //Handle save button action. } else if (e. get. Source() == save. Button) { int return. Val = fc. show. Save. Dialog(File. Chooser. Demo. this); if (return. Val == JFile. Chooser. APPROVE_OPTION) { File file = fc. get. Selected. File(); //This is where a real application would save the file. log. append("Saving: " + file. get. Name() + ". " + newline); } else { log. append("Save command cancelled by user. " + newline); } log. set. Caret. Position(log. get. Document(). get. Length()); } COP 4610 L: GUI Components Part 2 Page 28 Mark Llewellyn ©

} /** Returns an Image. Icon, or null if the path was invalid. */

} /** Returns an Image. Icon, or null if the path was invalid. */ protected static Image. Icon create. Image. Icon(String path) { java. net. URL img. URL = File. Chooser. Demo. class. get. Resource(path); if (img. URL != null) { return new Image. Icon(img. URL); } else { System. err. println("Couldn't find file: " + path); return null; } } // Create the GUI and show it. For thread safety, this method should be invoked from the // event-dispatching thread. public static void main(String[] args) { private static void create. And. Show. GUI() { //Schedule a job for the event//Make sure we have nice window decorations. dispatching thread: JFrame. set. Default. Look. And. Feel. Decorated(true); //creating and showing this JDialog. set. Default. Look. And. Feel. Decorated(true); application's GUI. //Create and set up the window. javax. swing. Swing. Utilities. invoke. La JFrame frame = new JFrame("File. Chooser. Demo"); ter(new Runnable() { frame. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); public void run() { //Create and set up the content pane. create. And. Show. GUI(); JComponent new. Content. Pane = new File. Chooser. Demo(); } new. Content. Pane. set. Opaque(true); //content panes must be opaque }); frame. set. Content. Pane(new. Content. Pane); } //Display the window. } frame. pack(); frame. set. Visible(true); } COP 4610 L: GUI Components Part 2 Page 29 Mark Llewellyn ©

Initial File. Chooser. Demo dialog This window is used to return status messages from

Initial File. Chooser. Demo dialog This window is used to return status messages from the File. Chooser Open dialog which appears after user clicks open button. Note that the argument to the show. Open. Dialog method specifies the parent component for the dialog. The parent component affects the position of the dialog and the frame that it depends on. The Java look and feel places the dialog directly over the parent component. COP 4610 L: GUI Components Part 2 Page 30 Mark Llewellyn ©

Initial File. Chooser. Demo dialog Save dialog which appears after user clicks save button.

Initial File. Chooser. Demo dialog Save dialog which appears after user clicks save button. Note that cursor is automatically placed in the file name box to await user entry of the name of the file to be saved. COP 4610 L: GUI Components Part 2 Page 31 Mark Llewellyn ©

Swing Text Components and HTML Rendering • Some of our previous examples illustrated the

Swing Text Components and HTML Rendering • Some of our previous examples illustrated the two of the three basic text components used for presenting and editing text. We’ve already seen JText. Field and JText. Area, and now we’ll look at a more sophisticated text component called a JEditor. Pane. • JEditor. Pane provides enhanced text-rendering capabilities. It supports styled documents that include formatting, font and color information. • JEditor. Pane is capable of rendering HTML documents as well as Rich Text Format (RTF) documents. • The following example utilizes the JEditor. Pane class to render HTML pages for a simple web browser application. COP 4610 L: GUI Components Part 2 Page 32 Mark Llewellyn ©

The Components of the Web Browser • The next example consists of three basic

The Components of the Web Browser • The next example consists of three basic components: 1. A Web. Browser. Pane which is an extension of class JEditor. Pane. Web. Browser. Pane creates a web browsing component that maintains a history of visited URLs. 2. Web. Tool. Bar is an extension of class JTool. Bar (JTool. Bar allows developers to add toolbars to GUIs to provide common functions such as cut, copy, paste, and navigation). This class provides commonly used navigation components for a Web. Browser. Pane. In this case a back button and forward button are provided. 3. Class Web. Browser uses a Web. Browser. Pane and a Web. Tool. Bar to create a simple web-browser application. COP 4610 L: GUI Components Part 2 Page 33 Mark Llewellyn ©

// Web. Browser. Pane. java // Web. Browser. Pane is a simple Web-browsing component

// Web. Browser. Pane. java // Web. Browser. Pane is a simple Web-browsing component that // extends JEditor. Pane and maintains a history of visited URLs. // Java core packages import java. util. *; import java. net. *; import java. io. *; // Java extension packages import javax. swing. *; import javax. swing. event. *; Web. Browser. Pane Class public class Web. Browser. Pane extends JEditor. Pane { JEditor. Pane enables hyperlinks in HTML documents only if the JEditor. Pane is not editable. private List history = new Array. List(); private int history. Index; // Web. Browser. Pane constructor public Web. Browser. Pane() { // disable editing to enable hyperlinks set. Editable( false ); } // display given URL and add it to history public void go. To. URL( URL url ) { display. Page( url ); COP 4610 L: GUI Components Part 2 Page 34 Mark Llewellyn ©

history. add( url ); history. Index = history. size() - 1; } // display

history. add( url ); history. Index = history. size() - 1; } // display next history URL in editor. Pane public URL forward() { history. Index++; // do not go past end of history if ( history. Index >= history. size() ) history. Index = history. size() - 1; URL url = ( URL ) history. get( history. Index ); display. Page( url ); return url; } // display previous history URL in editor. Pane public URL back() { history. Index--; // do not go past beginning of history if ( history. Index < 0 ) history. Index = 0; // display previous URL url = ( URL ) history. get( history. Index ); display. Page( url ); return url; } COP 4610 L: GUI Components Part 2 // display given URL in JEditor. Pane private void display. Page( URL page. URL ) { // display URL try { set. Page( page. URL ); } // handle exception reading from URL catch ( IOException io. Exception ) { io. Exception. print. Stack. Trace(); } } } Page 35 Mark Llewellyn ©

// Web. Tool. Bar. java // Web. Tool. Bar is a JTool. Bar subclass

// Web. Tool. Bar. java // Web. Tool. Bar is a JTool. Bar subclass that contains components // for navigating a Web. Browser. Pane. Web. Tool. Bar includes back // and forward buttons and a text field for entering URLs. // Java core packages import java. awt. *; import java. awt. event. *; import java. net. *; // Java extension packages import javax. swing. *; import javax. swing. event. *; Web. Tool. Bar Class public class Web. Tool. Bar extends JTool. Bar implements Hyperlink. Listener { private Web. Browser. Pane web. Browser. Pane; private JButton back. Button; private JButton forward. Button; private JText. Field url. Text. Field; // Web. Tool. Bar constructor public Web. Tool. Bar( Web. Browser. Pane browser ) { super( "Web Navigation" ); // register for Hyperlink. Events web. Browser. Pane = browser; web. Browser. Pane. add. Hyperlink. Listener( this ); // create JText. Field for entering URLs url. Text. Field = new JText. Field( 25 ); COP 4610 L: GUI Components Part 2 Page 36 Mark Llewellyn ©

url. Text. Field. add. Action. Listener( new Action. Listener() { // navigate web. Browser

url. Text. Field. add. Action. Listener( new Action. Listener() { // navigate web. Browser to user-entered URL public void action. Performed( Action. Event event ) { // attempt to load URL in web. Browser. Pane try { URL url = new URL( url. Text. Field. get. Text() ); web. Browser. Pane. go. To. URL( url ); } // handle invalid URL catch ( Malformed. URLException url. Exception ) { url. Exception. print. Stack. Trace(); } } } ); // create JButton for navigating to previous history URL back. Button = new JButton( new Image. Icon( get. Class(). get. Resource( "images/back. gif" ) ) ); back. Button. add. Action. Listener( new Action. Listener() { public void action. Performed( Action. Event event ) { // navigate to previous URL url = web. Browser. Pane. back(); // display URL in url. Text. Field. set. Text( url. to. String() ); } } ); COP 4610 L: GUI Components Part 2 Page 37 Mark Llewellyn ©

// create JButton for navigating to next history URL forward. Button = new JButton(

// create JButton for navigating to next history URL forward. Button = new JButton( new Image. Icon( get. Class(). get. Resource( "images/forward. gif" ) ) ); forward. Button. add. Action. Listener( new Action. Listener() { public void action. Performed( Action. Event event ) { // navigate to next URL url = web. Browser. Pane. forward(); // display new URL in url. Text. Field. set. Text( url. to. String() ); } } ); // add JButtons and JText. Field to Web. Tool. Bar add( back. Button ); add( forward. Button ); add( url. Text. Field ); } // end Web. Tool. Bar constructor // listen for Hyperlink. Events in Web. Browser. Pane public void hyperlink. Update( Hyperlink. Event event ) { // if hyperlink was activated, go to hyperlink's URL if ( event. get. Event. Type() == Hyperlink. Event. Type. ACTIVATED ) { // get URL from Hyperlink. Event URL url = event. get. URL(); // navigate to URL and display URL in url. Text. Field web. Browser. Pane. go. To. URL( url ); url. Text. Field. set. Text( url. to. String() ); } } } COP 4610 L: GUI Components Part 2 Page 38 Mark Llewellyn ©

// Web. Browser. java // Web. Browser is an application for browsing Web sites

// Web. Browser. java // Web. Browser is an application for browsing Web sites using // a Web. Tool. Bar and Web. Browser. Pane. // Java core packages import java. awt. *; import java. awt. event. *; import java. net. *; // Java extension packages import javax. swing. *; import javax. swing. event. *; Web. Browser Class public class Web. Browser extends JFrame { The previously private Web. Tool. Bar tool. Bar; defined classes private Web. Browser. Pane browser. Pane; // Web. Browser constructor public Web. Browser() { super( "COP 4610 L Simple Web Browser" ); // create Web. Browser. Pane and Web. Tool. Bar for navigation browser. Pane = new Web. Browser. Pane(); Recall that the default layout tool. Bar = new Web. Tool. Bar( browser. Pane ); manager for JFrame is a // lay out Web. Browser components Border. Layout. Container content. Pane = get. Content. Pane(); content. Pane. add( tool. Bar, Border. Layout. NORTH ); content. Pane. add( new JScroll. Pane( browser. Pane ), Border. Layout. CENTER ); } COP 4610 L: GUI Components Part 2 Page 39 Mark Llewellyn ©

// execute application public static void main( String args[] ) { Web. Browser browser

// execute application public static void main( String args[] ) { Web. Browser browser = new Web. Browser(); browser. set. Default. Close. Operation( EXIT_ON_CLOSE ); browser. set. Size( 640, 480 ); browser. set. Visible( true ); } } Web. Tool. Bar instance COP 4610 L: GUI Components Part 2 Page 40 Mark Llewellyn ©

Web. Tool. Bar instance has been moved by the user. COP 4610 L: GUI

Web. Tool. Bar instance has been moved by the user. COP 4610 L: GUI Components Part 2 Page 41 Mark Llewellyn ©

JSplit. Pane and JTabbed. Pane Components • JSplit. Pane and JTabbed. Pane are container

JSplit. Pane and JTabbed. Pane Components • JSplit. Pane and JTabbed. Pane are container components that enable application developers to present large amounts of information in a small screen area. • JSplit. Pane handles this by dividing two components with a divider the user can reposition to expand contract the visible area of the JSplit. Pane’s child components. – • A JSplit. Pane can contain only two child components, however, each child component may contain nested components. We’ll look at an example using a JSplit. Pane component and then we’ll examine the JTabbed. Pane component. COP 4610 L: GUI Components Part 2 Page 42 Mark Llewellyn ©

// Favorites. Web. Browser. java // Favorites. Web. Browser is an application for browsing

// Favorites. Web. Browser. java // Favorites. Web. Browser is an application for browsing Web sites // using a Web. Tool. Bar and Web. Browser. Pane and displaying an HTML // page containing links to favorite Web sites. // Java core packages import java. awt. *; import java. awt. event. *; import java. net. *; // Java extension packages import javax. swing. *; import javax. swing. event. *; Favorites. Web. Browser Class public class Favorites. Web. Browser extends JFrame { private Web. Tool. Bar tool. Bar; private Web. Browser. Pane browser. Pane; private Web. Browser. Pane favorites. Browser. Pane; // Web. Browser constructor public Favorites. Web. Browser() { super( "COP 4610 L - Favorites Web Browser" ); // create Web. Browser. Pane and Web. Tool. Bar for navigation browser. Pane = new Web. Browser. Pane(); tool. Bar = new Web. Tool. Bar( browser. Pane ); // create Web. Browser. Pane for displaying favorite sites favorites. Browser. Pane = new Web. Browser. Pane(); COP 4610 L: GUI Components Part 2 Page 43 Mark Llewellyn ©

// add Web. Tool. Bar as listener for Hyperlink. Events in favorites. Browser. Pane.

// add Web. Tool. Bar as listener for Hyperlink. Events in favorites. Browser. Pane. add. Hyperlink. Listener( tool. Bar ); // display favorites. html in favorites. Browser. Pane HTML file containing a list of favorites. Browser. Pane. go. To. URL( favorite URLs. get. Class(). get. Resource( "favorites. html" ) ); // create JSplit. Pane with horizontal split (side-by-side) // and add Web. Browser. Panes with JScroll. Panes JSplit. Pane split. Pane = new JSplit. Pane( The first argument indicates that the JSplit. Pane. HORIZONTAL_SPLIT, JSplit. Pane should display its child new JScroll. Pane( favorites. Browser. Pane ), components side by side. A verticalnew JScroll. Pane( browser. Pane ) ); split would display the two components // position divider between Web. Browser. Panes one on top of the other. The second split. Pane. set. Divider. Location( 210 ); two arguments are the components to // add buttons for expanding/contracting divider be divided in the JSplit. Pane. set. One. Touch. Expandable( true ); // lay out Web. Browser components Container content. Pane = get. Content. Pane(); Sets the position of the content. Pane. add( tool. Bar, Border. Layout. NORTH ); divider between the two content. Pane. add( split. Pane, Border. Layout. CENTER ); components. } // execute application public static void main( String args[] ) { Favorites. Web. Browser browser = new Favorites. Web. Browser(); browser. set. Default. Close. Operation( EXIT_ON_CLOSE ); browser. set. Size( 640, 480 ); browser. set. Visible( true ); } } COP 4610 L: GUI Components Part 2 Page 44 Adds two buttons to the divider to allow the user to expand or contract the divider to one side or the other with a single click. Mark Llewellyn ©

Buttons for expanding and contracting the split pane. Favorites menu in JSplit. Pane Two

Buttons for expanding and contracting the split pane. Favorites menu in JSplit. Pane Two separate panes in the JSplit. Pane COP 4610 L: GUI Components Part 2 Page 45 Mark Llewellyn ©

JTabbed. Pane Component • JTabbed. Pane presents multiple components in separate tabs, which the

JTabbed. Pane Component • JTabbed. Pane presents multiple components in separate tabs, which the user navigates between using a mouse or the keyboard. • The example application Tabbed. Pane. Web. Browser uses a JTabbed. Pane to enable a user to browse multiple webpages at one time within a single application window. • The user invokes an Action to add a new Web. Browser. Pane to the JTabbed. Pane. Each time the user adds a new Web. Browser. Pane, the JTabbed. Pane creates a new tab and places the Web. Browser. Pane in this new tab. COP 4610 L: GUI Components Part 2 Page 46 Mark Llewellyn ©

// Tabbed. Pane. Web. Browser. java // Tabbed. Pane. Web. Browser is an application

// Tabbed. Pane. Web. Browser. java // Tabbed. Pane. Web. Browser is an application that uses a // JTabbed. Pane to display multiple Web browsers. // Java core packages import java. awt. *; import java. awt. event. *; // Java extension packages import javax. swing. *; Tabbed. Pane. Web. Browser Class public class Tabbed. Pane. Web. Browser extends JFrame { // JTabbed. Pane for displaying multiple browser tabs private JTabbed. Pane tabbed. Pane = new JTabbed. Pane(); // Tabbed. Pane. Web. Browser constructor public Tabbed. Pane. Web. Browser() { super( "JTabbed. Pane Web Browser" ); // create first browser tab create. New. Tab(); // add JTabbed. Pane to content. Pane get. Content. Pane(). add( tabbed. Pane ); COP 4610 L: GUI Components Part 2 Page 47 Mark Llewellyn ©

// create File JMenu for creating new browser tabs and exiting application JMenu file.

// create File JMenu for creating new browser tabs and exiting application JMenu file. Menu = new JMenu( "File" ); file. Menu. add( new New. Tab. Action() ); file. Menu. add. Separator(); file. Menu. add( new Exit. Action() ); file. Menu. set. Mnemonic( 'F' ); JMenu. Bar menu. Bar = new JMenu. Bar(); menu. Bar. add( file. Menu ); set. JMenu. Bar( menu. Bar ); } // end Tabbed. Pane. Web. Browser constructor // create new browser tab private void create. New. Tab() { // create JPanel to contain Web. Browser. Pane and Web. Tool. Bar JPanel panel = new JPanel( new Border. Layout() ); // create Web. Browser. Pane and Web. Tool. Bar Web. Browser. Pane browser. Pane = new Web. Browser. Pane(); Web. Tool. Bar tool. Bar = new Web. Tool. Bar( browser. Pane ); // add Web. Browser. Pane and Web. Tool. Bar to JPanel panel. add( tool. Bar, Border. Layout. NORTH ); panel. add( new JScroll. Pane( browser. Pane ), Border. Layout. CENTER ); COP 4610 L: GUI Components Part 2 Page 48 Mark Llewellyn ©

// add JPanel to JTabbed. Pane tabbed. Pane. add. Tab( "Browser " + tabbed.

// add JPanel to JTabbed. Pane tabbed. Pane. add. Tab( "Browser " + tabbed. Pane. get. Tab. Count(), panel ); } // Action for creating new browser tabs private class New. Tab. Action extends Abstract. Action { // New. Tab. Action constructor public New. Tab. Action() { // set name, description and mnemonic key put. Value( Action. NAME, "New Browser Tab" ); put. Value( Action. SHORT_DESCRIPTION, "Create New Web Browser Tab" ); put. Value( Action. MNEMONIC_KEY, new Integer( 'N' ) ); } // when Action invoked, create new browser tab public void action. Performed( Action. Event event ) { create. New. Tab(); } } // Action for exiting application private class Exit. Action extends Abstract. Action { // Exit. Action constructor public Exit. Action() { // set name, description and mnemonic key put. Value( Action. NAME, "Exit" ); put. Value( Action. SHORT_DESCRIPTION, "Exit Application" ); put. Value( Action. MNEMONIC_KEY, new Integer( 'x' ) ); } COP 4610 L: GUI Components Part 2 Page 49 Mark Llewellyn ©

// when Action invoked, exit application public void action. Performed( Action. Event event )

// when Action invoked, exit application public void action. Performed( Action. Event event ) { System. exit( 0 ); } } // execute application public static void main( String args[] ) { Tabbed. Pane. Web. Browser browser = new Tabbed. Pane. Web. Browser(); browser. set. Default. Close. Operation( EXIT_ON_CLOSE ); browser. set. Size( 640, 480 ); browser. set. Visible( true ); } } Example with three tabbed browsers active. COP 4610 L: GUI Components Part 2 Page 50 Mark Llewellyn ©

Drag and Drop • Drag and drop is a common way to manipulate data

Drag and Drop • Drag and drop is a common way to manipulate data in a GUI. Most GUIs emulate real-world desktops, with icons that represent the objects on a virtual desk. • Drag and drop enables users to move items around the desktop and to move and copy data among applications using mouse gestures. • A mouse gesture is a mouse movement that correpsonds to a drag and drop operation, such as dragging a file from one folder location and dropping the file into another folder. • Two Java APIs enable drag and drop data transfer between applications. COP 4610 L: GUI Components Part 2 Page 51 Mark Llewellyn ©

The Data Transfer API and Drag and Drop API • The data transfer API

The Data Transfer API and Drag and Drop API • The data transfer API – package java. awt. datatransfer – enables copying and moving data within a single application or among multiple applications. • The drag and drop API enables Java applications to recognize drag and drop gestures and to respond to drag and drop operations. • A drag and drop operation uses the data transfer API to transfer the data from the drag source to the drop target. The application which is the drop target would use the drag and drop API to recognize that a drag and drop operation occurred and would use the data transfer API to retrieve the data transferred through the drag and drop operation. COP 4610 L: GUI Components Part 2 Page 52 Mark Llewellyn ©

A Drag and Drop Version of Our Web. Browser • The last example in

A Drag and Drop Version of Our Web. Browser • The last example in this section of notes presents a drag and drop version of the web browser that we have been developing. • In this case the application Dn. DWeb. Browser is an extension of our original web browser that also allows the user to drop a file onto the Web. Browser. Pane to view the file contents. – The user could drag and drop an HTML file from the host computer’s desktop (or other location) and drop the file on the Web. Browser. Pane to render the HTML. – The second method would be to open an HTML file containing URLs, then select a specific URL to drag and drop onto the web browser’s tool bar. Then from within the web browser, the user clicks the window and the web site contents are displayed. COP 4610 L: GUI Components Part 2 Page 53 Mark Llewellyn ©

// Dn. DWeb. Browser. java // Dn. DWeb. Browser is an application for viewing

// Dn. DWeb. Browser. java // Dn. DWeb. Browser is an application for viewing Web pages using drag and drop. A Drag and Drop // Java core packages Web. Browser Example import java. awt. *; import java. awt. dnd. *; import java. awt. datatransfer. *; import java. util. *; import java. io. *; import java. net. *; Create a // Java extension packages Web. Browser. Pane import javax. swing. *; and a Web. Tool. Bar import javax. swing. event. *; public class Dn. DWeb. Browser extends JFrame { private Web. Tool. Bar tool. Bar; private Web. Browser. Pane browser. Pane; // Dn. DWeb. Browser constructor public Dn. DWeb. Browser() { super( "Drag-and-Drop Web Browser" ); // create Web. Browser. Pane and Web. Tool. Bar for navigation browser. Pane = new Web. Browser. Pane(); tool. Bar = new Web. Tool. Bar( browser. Pane ); // enable Web. Browser. Pane to accept drop operations, using // Drop. Target. Handler as the Drop. Target. Listener browser. Pane. set. Drop. Target( new Drop. Target( browser. Pane, Dn. DConstants. ACTION_COPY, new Drop. Target. Handler() ) ); COP 4610 L: GUI Components Part 2 Page 54 Create a drop target within the browser. Pane object. The first argument is the GUI component onto which the user can drop objects. The second argument is the type of dnd operations supported. Third argument is the listener to be notified of dnd operation events. Mark Llewellyn ©

// lay out Web. Browser components Container content. Pane = get. Content. Pane(); content.

// lay out Web. Browser components Container content. Pane = get. Content. Pane(); content. Pane. add( tool. Bar, Border. Layout. NORTH ); content. Pane. add( new JScroll. Pane( browser. Pane ), Border. Layout. CENTER ); Drop. Target. Handler implements interface Drop. Target. Listener to listen for dnd operation events related to a Drop. Target. } // inner class to handle Drop. Target. Events private class Drop. Target. Handler implements Drop. Target. Listener { // handle drop operation public void drop( Drop. Target. Drop. Event event ) Handle drop event { // get dropped Transferable object Transferable transferable = event. get. Transferable(); Get the transferable object the user dropped. // if Transferable is a List of Files, accept drop if ( transferable. is. Data. Flavor. Supported( Data. Flavor. java. File. List. Flavor ) ) { // accept the drop operation to copy the object Represents a list of files event. accept. Drop( Dn. DConstants. ACTION_COPY ); // process list of files and display each in browser try { // get List of Files java. util. List file. List = ( java. util. List ) transferable. get. Transfer. Data( Data. Flavor. java. File. List. Flavor ); Iterator iterator = file. List. iterator(); COP 4610 L: GUI Components Part 2 Page 55 Mark Llewellyn ©

while ( iterator. has. Next() ) { File file = ( File ) iterator.

while ( iterator. has. Next() ) { File file = ( File ) iterator. next(); // display File in browser and complete drop browser. Pane. go. To. URL( file. to. URL() ); } // indicate successful drop event. drop. Complete( true ); Drag and drop operation was successful so close with argument true. } // handle exception if Data. Flavor not supported catch ( Unsupported. Flavor. Exception flavor. Exception ) { flavor. Exception. print. Stack. Trace(); event. drop. Complete( false ); } // handle exception reading Transferable data catch ( IOException io. Exception ) { io. Exception. print. Stack. Trace(); event. drop. Complete( false ); } } // if dropped object is not file list, reject drop else event. reject. Drop(); Dropped object was not a list of files so do not accept the dropped object. } COP 4610 L: GUI Components Part 2 Page 56 Mark Llewellyn ©

// handle drag operation entering Drop. Target public void drag. Enter( Drop. Target. Drag.

// handle drag operation entering Drop. Target public void drag. Enter( Drop. Target. Drag. Event event ) { // if data is java. File. List. Flavor, accept drag for copy if ( event. is. Data. Flavor. Supported( Data. Flavor. java. File. List. Flavor ) ) event. accept. Drag( Dn. DConstants. ACTION_COPY ); // reject all other Data. Flavors else event. reject. Drag(); } // invoked when drag operation exits Drop. Target public void drag. Exit( Drop. Target. Event event ) { } Invoked when the dnd operation enters a Drop. Target Dn. DConstants include ACTION_COPY for copying a dragged object. . ACTION_MOVE for moving a dropped object. ACTION_LINK for creating a link to an object. // invoked when drag operation occurs over Drop. Target public void drag. Over( Drop. Target. Drag. Event event ) { } Interface methods that do nothing in this case. // invoked if drop. Action changes (e. g. , from COPY to LINK) public void drop. Action. Changed( Drop. Target. Drag. Event event ) { } } // end class Drop. Target. Handler // execute application public static void main( String args[] ) { Dn. DWeb. Browser browser = new Dn. DWeb. Browser(); browser. set. Default. Close. Operation( EXIT_ON_CLOSE ); browser. set. Size( 640, 480 ); browser. set. Visible( true ); } } COP 4610 L: GUI Components Part 2 Page 57 Mark Llewellyn ©

Initial Browser Window After dragging favorites. html onto the web browser window. The HTML

Initial Browser Window After dragging favorites. html onto the web browser window. The HTML contents are rendered in the web browser window. COP 4610 L: GUI Components Part 2 Page 58 Mark Llewellyn ©

User opens favorites. html in another window to display the URLs contained in the

User opens favorites. html in another window to display the URLs contained in the file. Then a specific URL is selected and dragged onto the web browser tool bar and dropped. Once the URL is located in the window, the user clicks on this link and the web content is displayed in the browser window. COP 4610 L: GUI Components Part 2 Page 59 Mark Llewellyn ©