Presentation is loading. Please wait.

Presentation is loading. Please wait.

Graphic User Interface. Introduction to Graphics The last few sections of each chapter of the textbook focus on graphics and graphical user interfaces.

Similar presentations


Presentation on theme: "Graphic User Interface. Introduction to Graphics The last few sections of each chapter of the textbook focus on graphics and graphical user interfaces."— Presentation transcript:

1 Graphic User Interface

2 Introduction to Graphics The last few sections of each chapter of the textbook focus on graphics and graphical user interfaces A picture or drawing must be digitized for storage on a computer A picture is made up of pixels (picture elements), and each pixel is stored separately The number of pixels used to represent a picture is called the picture resolution The number of pixels that can be displayed by a monitor is called the monitor resolution © 2004 Pearson Addison-Wesley. All rights reserved2-2

3 Coordinate Systems Each pixel can be identified using a two-dimensional coordinate system When referring to a pixel in a Java program, we use a coordinate system with the origin in the top-left corner © 2004 Pearson Addison-Wesley. All rights reserved2-3 Y X(0, 0) (112, 40) 112 40

4 Representing Color A black and white picture could be stored using one bit per pixel (0 = white and 1 = black) A colored picture requires more information; there are several techniques for representing colors For example, every color can be represented as a mixture of the three additive primary colors Red, Green, and Blue Each color is represented by three numbers between 0 and 255 that collectively are called an RGB value © 2004 Pearson Addison-Wesley. All rights reserved2-4

5 The Color Class A color in a Java program is represented as an object created from the Color class The Color class also contains several predefined colors, including the following: © 2004 Pearson Addison-Wesley. All rights reserved2-5 Object Color.black Color.blue Color.cyan Color.orange Color.white Color.yellow RGB Value 0, 0, 0 0, 0, 255 0, 255, 255 255, 200, 0 255, 255, 255 255, 255, 0

6 Applets A Java application is a stand-alone program with a main method (like the ones we've seen so far) A Java applet is a program that is intended to transported over the Web and executed using a web browser An applet also can be executed using the appletviewer tool of the Java Software Development Kit An applet doesn't have a main method Instead, there are several special methods that serve specific purposes © 2004 Pearson Addison-Wesley. All rights reserved2-6

7 Applets The paint method, for instance, is executed automatically and is used to draw the applet’s contents The paint method accepts a parameter that is an object of the Graphics class A Graphics object defines a graphics context on which we can draw shapes and text The Graphics class has several methods for drawing shapes © 2004 Pearson Addison-Wesley. All rights reserved2-7

8 Applets The class that defines an applet extends the Applet class This makes use of inheritance, which is explored in more detail in Chapter 8 See Einstein.java (page 97)Einstein.java An applet is embedded into an HTML file using a tag that references the bytecode file of the applet The bytecode version of the program is transported across the web and executed by a Java interpreter that is part of the browser © 2004 Pearson Addison-Wesley. All rights reserved2-8

9 The HTML applet Tag © 2004 Pearson Addison-Wesley. All rights reserved2-9 The Einstein Applet

10 Drawing Shapes Let's explore some of the methods of the Graphics class that draw shapes in more detail A shape can be filled or unfilled, depending on which method is invoked The method parameters specify coordinates and sizes Shapes with curves, like an oval, are usually drawn by specifying the shape’s bounding rectangle An arc can be thought of as a section of an oval © 2004 Pearson Addison-Wesley. All rights reserved2-10

11 Drawing a Line © 2004 Pearson Addison-Wesley. All rights reserved2-11 X Y 10 20 150 45 page.drawLine (10, 20, 150, 45); page.drawLine (150, 45, 10, 20); or

12 Drawing a Rectangle © 2004 Pearson Addison-Wesley. All rights reserved2-12 X Y page.drawRect (50, 20, 100, 40); 50 20 100 40

13 Drawing an Oval © 2004 Pearson Addison-Wesley. All rights reserved2-13 X Y page.drawOval (175, 20, 50, 80); 175 20 50 80 bounding rectangle

14 Drawing Shapes Every drawing surface has a background color Every graphics context has a current foreground color Both can be set explicitly See Snowman.java (page103)Snowman.java © 2004 Pearson Addison-Wesley. All rights reserved2-14

15 Graphical Applications Except for the applets seen in Chapter 2, the example programs we've explored thus far have been text-based They are called command-line applications, which interact with the user using simple text prompts Let's examine some Java applications that have graphical components These components will serve as a foundation to programs that have true graphical user interfaces (GUIs) © 2004 Pearson Addison-Wesley. All rights reserved3-15

16 GUI Components A GUI component is an object that represents a screen element such as a button or a text field GUI-related classes are defined primarily in the java.awt and the javax.swing packages The Abstract Windowing Toolkit (AWT) was the original Java GUI package The Swing package provides additional and more versatile components Both packages are needed to create a Java GUI-based program © 2004 Pearson Addison-Wesley. All rights reserved3-16

17 GUI Containers A GUI container is a component that is used to hold and organize other components A frame is a container that is used to display a GUI- based Java application A frame is displayed as a separate window with a title bar – it can be repositioned and resized on the screen as needed A panel is a container that cannot be displayed on its own but is used to organize other components A panel must be added to another container to be displayed © 2004 Pearson Addison-Wesley. All rights reserved3-17

18 GUI Containers A GUI container can be classified as either heavyweight or lightweight A heavyweight container is one that is managed by the underlying operating system A lightweight container is managed by the Java program itself Occasionally this distinction is important A frame is a heavyweight container and a panel is a lightweight container © 2004 Pearson Addison-Wesley. All rights reserved3-18

19 Labels A label is a GUI component that displays a line of text Labels are usually used to display information or identify other components in the interface Let's look at a program that organizes two labels in a panel and displays that panel in a frame See Authority.java (page 144)Authority.java This program is not interactive, but the frame can be repositioned and resized © 2004 Pearson Addison-Wesley. All rights reserved3-19

20 Nested Panels Containers that contain other components make up the containment hierarchy of an interface This hierarchy can be as intricate as needed to create the visual effect desired The following example nests two panels inside a third panel – note the effect this has as the frame is resized See NestedPanels.java (page 146)NestedPanels.java © 2004 Pearson Addison-Wesley. All rights reserved3-20

21 Images Images are often used in a programs with a graphical interface Java can manage images in both JPEG and GIF formats As we've seen, a JLabel object can be used to display a line of text It can also be used to display an image That is, a label can be composed of text, and image, or both at the same time © 2004 Pearson Addison-Wesley. All rights reserved3-21

22 Images The ImageIcon class is used to represent an image that is stored in a label The position of the text relative to the image can be set explicitly The alignment of the text and image within the label can be set as well See LabelDemo.java (page 149)LabelDemo.java © 2004 Pearson Addison-Wesley. All rights reserved3-22

23 © 2004 Pearson Addison-Wesley. All rights reserved4-23 Graphical Objects Graphical User Interfaces Buttons and Text Fields

24 Graphical User Interfaces A Graphical User Interface (GUI) in Java is created with at least three kinds of objects: components events listeners We've previously discussed components, which are objects that represent screen elements labels, buttons, text fields, menus, etc. Some components are containers that hold and organize other components frames, panels, applets, dialog boxes © 2004 Pearson Addison-Wesley. All rights reserved4-24

25 Events An event is an object that represents some activity to which we may want to respond For example, we may want our program to perform some action when the following occurs: the mouse is moved the mouse is dragged a mouse button is clicked a graphical button is clicked a keyboard key is pressed a timer expires Events often correspond to user actions, but not always © 2004 Pearson Addison-Wesley. All rights reserved4-25

26 Events and Listeners The Java standard class library contains several classes that represent typical events Components, such as a graphical button, generate (or fire) an event when it occurs A listener object "waits" for an event to occur and responds accordingly We can design listener objects to take whatever actions are appropriate when an event occurs © 2004 Pearson Addison-Wesley. All rights reserved4-26

27 Events and Listeners © 2004 Pearson Addison-Wesley. All rights reserved4-27 Component A component object may generate an event Listener A corresponding listener object is designed to respond to the event Event When the event occurs, the component calls the appropriate method of the listener, passing an object that describes the event

28 GUI Development Generally we use components and events that are predefined by classes in the Java class library Therefore, to create a Java program that uses a GUI we must: instantiate and set up the necessary components implement listener classes for any events we care about establish the relationship between listeners and components that generate the corresponding events Let's now explore some new components and see how this all comes together © 2004 Pearson Addison-Wesley. All rights reserved4-28

29 Buttons A push button is a component that allows the user to initiate an action by pressing a graphical button using the mouse A push button is defined by the JButton class It generates an action event The PushCounter example displays a push button that increments a counter each time it is pushed See PushCounter.java (page 186)PushCounter.java See PushCounterPanel.java (page 187)PushCounterPanel.java © 2004 Pearson Addison-Wesley. All rights reserved4-29

30 Push Counter Example The components of the GUI are the button, a label to display the counter, a panel to organize the components, and the main frame The PushCounterPanel class is represents the panel used to display the button and label The PushCounterPanel class is derived from JPanel using inheritance The constructor of PushCounterPanel sets up the elements of the GUI and initializes the counter to zero © 2004 Pearson Addison-Wesley. All rights reserved4-30

31 Push Counter Example The ButtonListener class is the listener for the action event generated by the button It is implemented as an inner class, which means it is defined within the body of another class That facilitates the communication between the listener and the GUI components Inner classes should only be used in situations where there is an intimate relationship between the two classes and the inner class is not needed in any other context © 2004 Pearson Addison-Wesley. All rights reserved4-31

32 Push Counter Example Listener classes are written by implementing a listener interface The ButtonListener class implements the ActionListener interface An interface is a list of methods that the implementing class must define The only method in the ActionListener interface is the actionPerformed method The Java class library contains interfaces for many types of events We discuss interfaces in more detail in Chapter 6 © 2004 Pearson Addison-Wesley. All rights reserved4-32

33 Push Counter Example The PushCounterPanel constructor: instantiates the ButtonListener object establishes the relationship between the button and the listener by the call to addActionListener When the user presses the button, the button component creates an ActionEvent object and calls the actionPerformed method of the listener The actionPerformed method increments the counter and resets the text of the label © 2004 Pearson Addison-Wesley. All rights reserved4-33

34 Text Fields Let's look at another GUI example that uses another type of component A text field allows the user to enter one line of input If the cursor is in the text field, the text field component generates an action event when the enter key is pressed See Fahrenheit.java (page 190)Fahrenheit.java See FahrenheitPanel.java (page 191)FahrenheitPanel.java © 2004 Pearson Addison-Wesley. All rights reserved4-34

35 Fahrenheit Example Like the PushCounter example, the GUI is set up in a separate panel class The TempListener inner class defines the listener for the action event generated by the text field The FahrenheitPanel constructor instantiates the listener and adds it to the text field When the user types a temperature and presses enter, the text field generates the action event and calls the actionPerformed method of the listener The actionPerformed method computes the conversion and updates the result label © 2004 Pearson Addison-Wesley. All rights reserved4-35

36 © 2004 Pearson Addison-Wesley. All rights reserved5-36 Decisions and Graphics More Components

37 Drawing Techniques Conditionals and loops enhance our ability to generate interesting graphics See Bullseye.java (page 252)Bullseye.java See BullseyePanel.java (page 253)BullseyePanel.java See Boxes.java (page 255)Boxes.java See BoxesPanel.java (page 256)BoxesPanel.java © 2004 Pearson Addison-Wesley. All rights reserved5-37

38 Determining Event Sources Recall that interactive GUIs require establishing a relationship between components and the listeners that respond to component events One listener object can be used to listen to two different components The source of the event can be determined by using the getSource method of the event passed to the listener See LeftRight.java (page 258)LeftRight.java See LeftRightPanel.java (page 259)LeftRightPanel.java © 2004 Pearson Addison-Wesley. All rights reserved5-38

39 Dialog Boxes A dialog box is a window that appears on top of any currently active window It may be used to: convey information confirm an action allow the user to enter data pick a color choose a file A dialog box usually has a specific, solitary purpose, and the user interaction with it is brief © 2004 Pearson Addison-Wesley. All rights reserved5-39

40 Dialog Boxes The JOptionPane class provides methods that simplify the creation of some types of dialog boxes See EvenOdd.java (page 262)EvenOdd.java We examine dialog boxes for choosing colors and files in Chapter 9 © 2004 Pearson Addison-Wesley. All rights reserved5-40

41 Check Boxes A check box is a button that can be toggled on or off It is represented by the JCheckBox class Unlike a push button, which generates an action event, a check box generates an item event whenever it changes state (is checked on or off) The ItemListener interface is used to define item event listeners The check box calls the itemStateChanged method of the listener when it is toggled © 2004 Pearson Addison-Wesley. All rights reserved5-41

42 Check Boxes Let's examine a program that uses check boxes to determine the style of a label's text string It uses the Font class, which represents a character font's: family name (such as Times or Courier) style (bold, italic, or both) font size See StyleOptions.java (page 265)StyleOptions.java See StyleOptionsPanel.java (page 266)StyleOptionsPanel.java © 2004 Pearson Addison-Wesley. All rights reserved5-42

43 Radio Buttons A group of radio buttons represents a set of mutually exclusive options – only one can be selected at any given time When a radio button from a group is selected, the button that is currently "on" in the group is automatically toggled off To define the group of radio buttons that will work together, each radio button is added to a ButtonGroup object A radio button generates an action event © 2004 Pearson Addison-Wesley. All rights reserved5-43

44 Radio Buttons Let's look at a program that uses radio buttons to determine which line of text to display See QuoteOptions.java (page 269) QuoteOptions.java See QuoteOptionsPanel.java (page 270) QuoteOptionsPanel.java Compare and contrast check boxes and radio buttons Check boxes work independently to provide a boolean option Radio buttons work as a group to provide a set of mutually exclusive options © 2004 Pearson Addison-Wesley. All rights reserved5-44

45 © 2004 Pearson Addison-Wesley. All rights reserved6-45 GUI Design and Layout

46 GUI Design We must remember that the goal of software is to help the user solve the problem To that end, the GUI designer should: Know the user Prevent user errors Optimize user abilities Be consistent Let's discuss each of these in more detail © 2004 Pearson Addison-Wesley. All rights reserved6-46

47 Know the User Knowing the user implies an understanding of: the user's true needs the user's common activities the user's level of expertise in the problem domain and in computer processing We should also realize these issues may differ for different users Remember, to the user, the interface is the program © 2004 Pearson Addison-Wesley. All rights reserved6-47

48 Prevent User Errors Whenever possible, we should design user interfaces that minimize possible user mistakes We should choose the best GUI components for each task For example, in a situation where there are only a few valid options, using a menu or radio buttons would be better than an open text field Error messages should guide the user appropriately © 2004 Pearson Addison-Wesley. All rights reserved6-48

49 Optimize User Abilities Not all users are alike – some may be more familiar with the system than others Knowledgeable users are sometimes called power users We should provide multiple ways to accomplish a task whenever reasonable "wizards" to walk a user through a process short cuts for power users Help facilities should be available but not intrusive © 2004 Pearson Addison-Wesley. All rights reserved6-49

50 Be Consistent Consistency is important – users get used to things appearing and working in certain ways Colors should be used consistently to indicate similar types of information or processing Screen layout should be consistent from one part of a system to another For example, error messages should appear in consistent locations © 2004 Pearson Addison-Wesley. All rights reserved6-50

51 Layout Managers A layout manager is an object that determines the way that components are arranged in a container There are several predefined layout managers defined in the Java standard class library: © 2004 Pearson Addison-Wesley. All rights reserved6-51 Defined in the AWT Defined in Swing Flow Layout Border Layout Card Layout Grid Layout GridBag Layout Box Layout Overlay Layout

52 Layout Managers Every container has a default layout manager, but we can explicitly set the layout manager as well Each layout manager has its own particular rules governing how the components will be arranged Some layout managers pay attention to a component's preferred size or alignment, while others do not A layout manager attempts to adjust the layout as components are added and as containers are resized © 2004 Pearson Addison-Wesley. All rights reserved6-52

53 Layout Managers We can use the setLayout method of a container to change its layout manager JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); The following example uses a tabbed pane, a container which permits one of several panes to be selected See LayoutDemo.java (page 340) LayoutDemo.java See IntroPanel.java (page 341) IntroPanel.java © 2004 Pearson Addison-Wesley. All rights reserved6-53

54 Flow Layout Flow layout puts as many components as possible on a row, then moves to the next row Rows are created as needed to accommodate all of the components Components are displayed in the order they are added to the container Each row of components is centered horizontally in the window by default, but could also be aligned left or right Also, the horizontal and vertical gaps between the components can be explicitly set See FlowPanel.java (page 343) FlowPanel.java © 2004 Pearson Addison-Wesley. All rights reserved6-54

55 Border Layout A border layout defines five areas into which components can be added © 2004 Pearson Addison-Wesley. All rights reserved6-55 North South CenterEastWest

56 Border Layout Each area displays one component (which could be a container such as a JPanel ) Each of the four outer areas enlarges as needed to accommodate the component added to it If nothing is added to the outer areas, they take up no space and other areas expand to fill the void The center area expands to fill space as needed See BorderPanel.java (page 346) BorderPanel.java © 2004 Pearson Addison-Wesley. All rights reserved6-56

57 Grid Layout A grid layout presents a container’s components in a rectangular grid of rows and columns One component is placed in each cell of the grid, and all cells have the same size As components are added to the container, they fill the grid from left-to-right and top-to-bottom (by default) The size of each cell is determined by the overall size of the container See GridPanel.java (page 349) GridPanel.java © 2004 Pearson Addison-Wesley. All rights reserved6-57

58 Box Layout A box layout organizes components horizontally (in one row) or vertically (in one column) Components are placed top-to-bottom or left-to- right in the order in which they are added to the container By combining multiple containers using box layout, many different configurations can be created Multiple containers with box layouts are often preferred to one container that uses the more complicated gridbag layout manager © 2004 Pearson Addison-Wesley. All rights reserved6-58

59 Box Layout Invisible components can be added to a box layout container to take up space between components Rigid areas have a fixed size Glue specifies where excess space should go A rigid area is created using the createRigidArea method of the Box class Glue is created using the createHorizontalGlue or createVerticalGlue methods See BoxPanel.java (page 352) BoxPanel.java © 2004 Pearson Addison-Wesley. All rights reserved6-59

60 Borders A border can be put around any Swing component to define how the edges of the component should be drawn Borders can be used effectively to group components visually The BorderFactory class contains several static methods for creating border objects A border is applied to a component using the setBorder method © 2004 Pearson Addison-Wesley. All rights reserved6-60

61 Borders An empty border buffers the space around the edge of a component otherwise has no visual effect A line border surrounds the component with a simple line the line's color and thickness can be specified An etched border creates the effect of an etched groove around a component uses colors for the highlight and shadow © 2004 Pearson Addison-Wesley. All rights reserved6-61

62 Borders A bevel border can be raised or lowered uses colors for the outer and inner highlights and shadows A titled border places a title on or around the border the title can be oriented in many ways A matte border specifies the sizes of the top, left, bottom, and right edges of the border separately uses either a solid color or an image © 2004 Pearson Addison-Wesley. All rights reserved6-62

63 Borders A compound border is a combination of two borders one or both of the borders can be a compound border See BorderDemo.java (page 355) BorderDemo.java © 2004 Pearson Addison-Wesley. All rights reserved6-63

64 © 2004 Pearson Addison-Wesley. All rights reserved7-64 Mouse Events and Key Events

65 Mouse Events Events related to the mouse are separated into mouse events and mouse motion events Mouse Events: mouse pressedthe mouse button is pressed down mouse releasedthe mouse button is released mouse clickedthe mouse button is pressed down and released without moving the mouse in between mouse enteredthe mouse pointer is moved onto (over) a component mouse exitedthe mouse pointer is moved off of a component © 2004 Pearson Addison-Wesley. All rights reserved7-65

66 Mouse Events Mouse Motion Events: mouse movedthe mouse is moved mouse draggedthe mouse is moved while the mouse button is pressed down © 2004 Pearson Addison-Wesley. All rights reserved7-66 Listeners for mouse events are created using the MouseListener and MouseMotionListener interfaces A MouseEvent object is passed to the appropriate method when a mouse event occurs

67 Mouse Events For a given program, we may only care about one or two mouse events To satisfy the implementation of a listener interface, empty methods must be provided for unused events See Dots.java (page 413) Dots.java See DotsPanel.java (page 414) DotsPanel.java © 2004 Pearson Addison-Wesley. All rights reserved7-67

68 Mouse Events Rubberbanding is the visual effect in which a shape is "stretched" as it is drawn using the mouse The following example continually redraws a line as the mouse is dragged See RubberLines.java (page 417) RubberLines.java See RubberLinesPanel.java (page 418) RubberLinesPanel.java © 2004 Pearson Addison-Wesley. All rights reserved7-68

69 Key Events A key event is generated when the user types on the keyboard key presseda key on the keyboard is pressed down key releaseda key on the keyboard is released key typeda key on the keyboard is pressed down and released © 2004 Pearson Addison-Wesley. All rights reserved7-69 Listeners for key events are created by implementing the KeyListener interface A KeyEvent object is passed to the appropriate method when a key event occurs

70 Key Events The component that generates a key event is the one that has the current keyboard focus Constants in the KeyEvent class can be used to determine which key was pressed The following example "moves" an image of an arrow as the user types the keyboard arrow keys See Direction.java (page 421) Direction.java See DirectionPanel.java (page 422) DirectionPanel.java © 2004 Pearson Addison-Wesley. All rights reserved7-70

71 © 2004 Pearson Addison-Wesley. All rights reserved8-71 Inheritance and GUIs The Timer Class

72 Designing for Inheritance As we've discussed, taking the time to create a good software design reaps long-term benefits Inheritance issues are an important part of an object- oriented design Properly designed inheritance relationships can contribute greatly to the elegance, maintainabilty, and reuse of the software Let's summarize some of the issues regarding inheritance that relate to a good software design © 2004 Pearson Addison-Wesley. All rights reserved8-72

73 Inheritance Design Issues Every derivation should be an is-a relationship Think about the potential future of a class hierarchy, and design classes to be reusable and flexible Find common characteristics of classes and push them as high in the class hierarchy as appropriate Override methods as appropriate to tailor or change the functionality of a child Add new variables to children, but don't redefine (shadow) inherited variables © 2004 Pearson Addison-Wesley. All rights reserved8-73

74 Inheritance Design Issues Allow each class to manage its own data; use the super reference to invoke the parent's constructor to set up its data Even if there are no current uses for them, override general methods such as toString and equals with appropriate definitions Use abstract classes to represent general concepts that lower classes have in common Use visibility modifiers carefully to provide needed access without violating encapsulation © 2004 Pearson Addison-Wesley. All rights reserved8-74

75 Restricting Inheritance The final modifier can be used to curtail inheritance If the final modifier is applied to a method, then that method cannot be overridden in any descendent classes If the final modifier is applied to an entire class, then that class cannot be used to derive any children at all Thus, an abstract class cannot be declared as final These are key design decisions, establishing that a method or class should be used as is © 2004 Pearson Addison-Wesley. All rights reserved8-75

76 The Component Class Hierarchy The Java classes that define GUI components are part of a class hierarchy Swing GUI components typically are derived from the JComponent class which is derived from the Container class which is derived from the Component class Many Swing components can serve as (limited) containers, because they are derived from the Container class For example, a JLabel object can contain an ImageIcon © 2004 Pearson Addison-Wesley. All rights reserved8-76

77 The Component Class Hierarchy An applet is a good example of inheritance Recall that when we define an applet, we extend the Applet class or the JApplet class The Applet and JApplet classes already handle all the details about applet creation and execution, including: interaction with a Web browser accepting applet parameters through HTML enforcing security restrictions © 2004 Pearson Addison-Wesley. All rights reserved8-77

78 The Component Class Hierarchy Our applet classes only have to deal with issues that specifically relate to what our particular applet will do When we define paintComponent method of an applet, we are actually overriding a method defined originally in the JComponent class and inherited by the JApplet class © 2004 Pearson Addison-Wesley. All rights reserved8-78

79 Event Adapter Classes Inheritance also gives us a alternate technique for creating listener classes We've seen that listener classes can be created by implementing a particular interface, such as MouseListener We can also create a listener class by extending an event adapter class Each listener interface that has more than one method has a corresponding adapter class, such as the MouseAdapter class © 2004 Pearson Addison-Wesley. All rights reserved8-79

80 Event Adapter Classes Each adapter class implements the corresponding listener and provides empty method definitions When you derive a listener class from an adapter class, you only need to override the event methods that pertain to the program Empty definitions for unused event methods do not need to be defined because they are provided via inheritance See OffCenter.java (page 466) OffCenter.java See OffCenterPanel.java (page 467) OffCenterPanel.java © 2004 Pearson Addison-Wesley. All rights reserved8-80

81 The Timer Class The Timer class of the javax.swing package is a GUI component, but it has no visual representation A Timer object generates an action event at specified intervals Timers can be used to manage any events that are based on a timed interval, such as an animation To create the illusion of movement, we use a timer to change the scene after an appropriate delay © 2004 Pearson Addison-Wesley. All rights reserved8-81

82 The Timer Class The start and stop methods of the Timer class start and stop the timer The delay can be set using the Timer constructor or using the setDelay method See Rebound.java (page 471) Rebound.java See ReboundPanel.java (page 472) ReboundPanel.java © 2004 Pearson Addison-Wesley. All rights reserved8-82

83 © 2004 Pearson Addison-Wesley. All rights reserved9-83 Event Processing Revisited File Choosers and Color Choosers Sliders

84 Event Processing Polymorphism plays an important role in the development of a Java graphical user interface As we've seen, we establish a relationship between a component and a listener: JButton button = new JButton(); button.addActionListener(new MyListener()); Note that the addActionListener method is accepting a MyListener object as a parameter In fact, we can pass the addActionListener method any object that implements the ActionListener interface © 2004 Pearson Addison-Wesley. All rights reserved9-84

85 Event Processing The source code for the addActionListener method accepts a parameter of type ActionListener (the interface) Because of polymorphism, any object that implements that interface is compatible with the parameter reference variable The component can call the actionPerformed method because of the relationship between the listener class and the interface Extending an adapter class to create a listener represents the same situation; the adapter class implements the appropriate interface already © 2004 Pearson Addison-Wesley. All rights reserved9-85

86 Dialog Boxes Recall that a dialog box is a small window that "pops up" to interact with the user for a brief, specific purpose The JOptionPane class makes it easy to create dialog boxes for presenting information, confirming an action, or accepting an input value Let's now look at two other classes that let us create specialized dialog boxes © 2004 Pearson Addison-Wesley. All rights reserved9-86

87 File Choosers Situations often arise where we want the user to select a file stored on a disk drive, usually so that its contents can be read and processed A file chooser, represented by the JFileChooser class, simplifies this process The user can browse the disk and filter the file types displayed See DisplayFile.java (page 516) DisplayFile.java © 2004 Pearson Addison-Wesley. All rights reserved9-87

88 Color Choosers In many situations we want to allow the user to select a color A color chooser, represented by the JColorChooser class, simplifies this process The user can choose a color from a palette or specify the color using RGB values See DisplayColor.java (page 519) DisplayColor.java © 2004 Pearson Addison-Wesley. All rights reserved9-88

89 Sliders A slider is a GUI component that allows the user to specify a value within a numeric range A slider can be oriented vertically or horizontally and can have optional tick marks and labels The minimum and maximum values for the slider are set using the JSlider constructor A slider produces a change event when the slider is moved, indicating that the slider and the value it represents has changed © 2004 Pearson Addison-Wesley. All rights reserved9-89

90 Sliders The following example uses three sliders to change values representing the color components of an RGB value See SlideColor.java (page 522) SlideColor.java See SlideColorPanel.java (page 523) SlideColorPanel.java © 2004 Pearson Addison-Wesley. All rights reserved9-90

91 © 2004 Pearson Addison-Wesley. All rights reserved10-91 Tool Tips and Mnemonics Combo Boxes Scroll Panes and Split Panes

92 Tool Tips A tool tip provides a short pop-up description when the mouse cursor rests momentarily on a component A tool tip is assigned using the setToolTipText method of a Swing component JButton button = new JButton ("Compute"); button.setToolTipText ("Calculate size"); © 2004 Pearson Addison-Wesley. All rights reserved10-92

93 Mnemonics A mnemonic is a keyboard alternative for pushing a button or selecting a menu option The mnemonic character should be chosen from the component's label, and is underlined The user activates the component by holding down the ALT key and pressing the mnemonic character A mnemonic is established using the setMnemonic method: JButton button = new JButton ("Calculate"); button.setMnemonic ("C"); © 2004 Pearson Addison-Wesley. All rights reserved10-93

94 Disabled Components Components can be disabled if they should not be used A disabled component is "grayed out" and will not respond to user interaction The status is set using the setEnabled method: JButton button = new JButton (“Do It”); button.setEnabled (false); © 2004 Pearson Addison-Wesley. All rights reserved10-94

95 GUI Design The right combination of special features such as tool tips and mnemonics can enhance the usefulness of a GUI See LightBulb.java (page 551) LightBulb.java See LightBulbPanel.java (page 553) LightBulbPanel.java See LightBulbControls.java (page 554) LightBulbControls.java © 2004 Pearson Addison-Wesley. All rights reserved10-95

96 Outline © 2004 Pearson Addison-Wesley. All rights reserved10-96 Tool Tips and Mnemonics Combo Boxes Scroll Panes and Split Panes

97 Combo Boxes A combo box provides a menu from which the user can choose one of several options The currently selected option is shown in the combo box A combo box shows its options only when the user presses it using the mouse Options can be established using an array of strings or using the addItem method © 2004 Pearson Addison-Wesley. All rights reserved10-97

98 The JukeBox Program A combo box generates an action event when the user makes a selection from it See JukeBox.java (page 557)JukeBox.java See JukeBoxControls.java (page 559)JukeBoxControls.java © 2004 Pearson Addison-Wesley. All rights reserved10-98

99 Outline © 2004 Pearson Addison-Wesley. All rights reserved10-99 Exception Handling The try-catch Statement Exception Classes I/O Exceptions Tool Tips and Mnemonics Combo Boxes Scroll Panes and Split Panes

100 Scroll Panes A scroll pane is useful for images or information too large to fit in a reasonably-sized area A scroll pane offers a limited view of the component it contains It provides vertical and/or horizontal scroll bars that allow the user to scroll to other areas of the component No event listener is needed for a scroll pane See TransitMap.java (page 562) TransitMap.java © 2004 Pearson Addison-Wesley. All rights reserved10-100

101 Split Panes A split pane ( JSplitPane ) is a container that displays two components separated by a moveable divider bar The two components can be displayed side by side, or one on top of the other © 2004 Pearson Addison-Wesley. All rights reserved10-101 Moveable Divider Bar Left Component Right Component Top Component Bottom Component

102 Split Panes The orientation of the split pane is set using the HORIZONTAL_SPLIT or VERTICAL_SPLIT constants The divider bar can be set so that it can be fully expanded with one click of the mouse The components can be continuously adjusted as the divider bar is moved, or wait until it stops moving Split panes can be nested © 2004 Pearson Addison-Wesley. All rights reserved10-102

103 Lists The Swing Jlist class represents a list of items from which the user can choose The contents of a JList object can be specified using an array of objects A JList object generates a list selection event when the current selection changes See PickImage.java (page 566) PickImage.java See ListPanel.java (page 568) ListPanel.java © 2004 Pearson Addison-Wesley. All rights reserved10-103

104 Lists A JList object can be set so that multiple items can be selected at the same time The list selection mode can be one of three options: single selection – only one item can be selected at a time single interval selection – multiple, contiguous items can be selected at a time multiple interval selection – any combination of items can be selected The list selection mode is defined by a ListSelectionModel object © 2004 Pearson Addison-Wesley. All rights reserved10-104

105 Menu © 2004 Pearson Addison-Wesley. All rights reserved8-105

106 MDI © 2004 Pearson Addison-Wesley. All rights reserved8-106


Download ppt "Graphic User Interface. Introduction to Graphics The last few sections of each chapter of the textbook focus on graphics and graphical user interfaces."

Similar presentations


Ads by Google