Java GUI Programs: Applets and Applications

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

Which of the following best describes a stand-alone application in Java, as opposed to an applet?

  • It runs within a web browser environment.
  • It requires a specific plugin to execute.
  • It is limited to performing simple tasks due to security restrictions.
  • It runs independently, without needing a web browser. (correct)

A GUI program's main routine typically outlines every step of the program's execution from start to finish, similar to a command-line program.

False (B)

In Java GUI programming, what is the primary role of the JOptionPane class?

displaying simple dialog boxes

Before a JFrame becomes visible on the screen, its size and location are typically set using the methods setSize() and ______().

<p>setLocation</p> Signup and view all the answers

Match the following GUI components with their descriptions:

<p>JFrame = An independent window that can serve as the main window of an application. JPanel = A container that can hold other components or be used as a drawing surface. JButton = A push button that triggers an action when clicked. BorderLayout = A layout manager that arranges components in the north, south, east, west, and center regions.</p> Signup and view all the answers

Which class is commonly subclassed to create a custom drawing surface in a Java GUI?

<p>JPanel (B)</p> Signup and view all the answers

The paintComponent() method of a JPanel should be called directly by the programmer to force a redraw of the component.

<p>False (B)</p> Signup and view all the answers

What method is used to add a component to a container in Java GUI programming?

<p>add()</p> Signup and view all the answers

A ______ is an object that implements a policy for arranging components inside a container.

<p>layout manager</p> Signup and view all the answers

Match the layout managers with their layout behaviors:

<p>FlowLayout = Arranges components in a row, wrapping to the next row if necessary. BorderLayout = Arranges components in the north, south, east, west, and center. GridLayout = Arranges components in a grid of rows and columns. BoxLayout = Arranges components in a single row or column.</p> Signup and view all the answers

What is the primary purpose of an event listener in Java GUI programming?

<p>To respond to events generated by user actions or system events. (D)</p> Signup and view all the answers

An object can listen for events even if its class does not explicitly implement the corresponding listener interface.

<p>False (B)</p> Signup and view all the answers

What method is called to register an event listener with a component in Java?

<p>addActionListener</p> Signup and view all the answers

The ______ interface must be implemented by a class for it to act as a listener for action events, such as button clicks.

<p>ActionListener</p> Signup and view all the answers

Match the event listener interfaces with the corresponding event types:

<p>ActionListener = Action events (e.g., button clicks) MouseListener = Mouse events (e.g., mouse clicks, mouse entered/exited) KeyListener = Key events (e.g., key presses, key releases) MouseMotionListener = Mouse motion events (e.g., mouse moved, mouse dragged)</p> Signup and view all the answers

Which method of the Graphics class is used to draw a filled rectangle?

<p>fillRect() (A)</p> Signup and view all the answers

The coordinate system in Java GUI programming has its origin (0,0) at the bottom-left corner of the component.

<p>False (B)</p> Signup and view all the answers

What are the three components of an RGB color in Java?

<p>red, green, blue</p> Signup and view all the answers

The setColor() method of a Graphics object takes a ______ object as its parameter to set the current drawing color.

<p>Color</p> Signup and view all the answers

Match the Font style constants with their descriptions:

<p>Font.PLAIN = Normal text style. Font.BOLD = Bold text style. Font.ITALIC = Italic text style. Font.BOLD + Font.ITALIC = Bold and italic text style.</p> Signup and view all the answers

Which method is used to change the current font of a Graphics object?

<p>setFont() (A)</p> Signup and view all the answers

The drawString() method draws a string with the baseline of the text at the specified y-coordinate.

<p>True (A)</p> Signup and view all the answers

What is the purpose of the repaint() method in Java GUI programming?

<p>requests a redraw of the component</p> Signup and view all the answers

In the HSB color model, the B stands for ______.

<p>brightness</p> Signup and view all the answers

Match the Graphics methods with the shapes they draw:

<p>drawOval() = Outline of an oval. fillRect() = Filled rectangle. drawLine() = Straight line. drawArc() = Arc of an oval.</p> Signup and view all the answers

When handling mouse events, which method is called when a mouse button is pressed and released without moving the mouse?

<p>mouseClicked() (D)</p> Signup and view all the answers

Pressing the right mouse button is always equivalent to holding down the ALT key while pressing the left mouse button in Java.

<p>False (B)</p> Signup and view all the answers

What methods can be called from a MouseEvent object to get the x and y coordinates of the mouse cursor?

<p>getX() and getY()</p> Signup and view all the answers

To detect mouse movements while a button is pressed, you should implement the ______ interface.

<p>MouseMotionListener</p> Signup and view all the answers

Match mouse events with actions:

<p>mousePressed = Triggered when a mouse button is initially pressed down. mouseReleased = Triggered when a depressed mouse button is released. mouseEntered = Triggered when the mouse cursor enters a defined component area. mouseExited = Triggered when the mouse cursor exits a defined component area.</p> Signup and view all the answers

Which of the following is NOT a valid way to specify the style of text using the Font class?

<p>Font.UNDERLINE (B)</p> Signup and view all the answers

Graphics2D is an interface in Java that provides advanced 2D rendering capabilities.

<p>False (B)</p> Signup and view all the answers

What is the first step you should take when defining a subclass of JPanel for use as a drawing surface?

<p>Call super.paintComponent(g);</p> Signup and view all the answers

The screen of a computer is essentially a grid of small squares known as ______.

<p>pixels</p> Signup and view all the answers

Match the HSB color components with their effects.

<p>H (Hue): = Determines the base color, ranging through shades in the color spectrum. S (Saturation): = Affects the color's purity; reducing saturation moves the color closer to gray. B (Brightness): = Influences the lightness or darkness of the color.</p> Signup and view all the answers

Why is it generally considered bad practice to obtain a graphics context using getGraphics() and draw directly, outside of the paintComponent() method?

<p>Changes may not persist when the component is redrawn by the system. (B)</p> Signup and view all the answers

Java requires that to use an interface, a class must only include the methods specified in the interface, not necessary to declare that the class implements the interface itself.

<p>False (B)</p> Signup and view all the answers

When is the mouseMoved() method called?

<p>when the mouse is moved while no mouse buttons are pressed</p> Signup and view all the answers

The coordinates obtained from a MouseEvent are expressed relative to the ______ that generated the event.

<p>component</p> Signup and view all the answers

Match the methods to test for modifier keys with actions:

<p>isShiftDown() = Checks if the Shift key is pressed. isControlDown() = Checks if the Control key is pressed. isAltDown() = Checks if the Alt (or Option) key is pressed. isMetaDown() = Checks if the Meta (or Command/Apple) key is pressed.</p> Signup and view all the answers

Flashcards

Stand-alone Application

A program that runs on its own, not in a web browser.

Applet

A program that runs within a rectangular area on a Web page.

main() Routine

The main method in this provides the start and end point of the specific program, such as a stand-alone application.

GUI Component

An object that provides a graphical way for users to interace with the computer. Examples: windows, menus, buttons, etc.

Signup and view all the flashcards

JOptionPane.showMessageDialog()

Creates a simple dialog box to display a message.

Signup and view all the flashcards

JFrame

An independent window that can serve as the main window of an application.

Signup and view all the flashcards

JPanel

A blank rectangular area that can contain other components or be drawn on.

Signup and view all the flashcards

paintComponent(Graphics g)

Method called automatically to draw a component; override to customize drawing.

Signup and view all the flashcards

Layout Manager

Arranges components within a container.

Signup and view all the flashcards

BorderLayout

Arranges components in north, south, east, west, and center positions.

Signup and view all the flashcards

Event Listener

An object that listens for events and responds by executing event-handling methods.

Signup and view all the flashcards

actionPerformed(ActionEvent e)

The method to handle events when a button is clicked.

Signup and view all the flashcards

addActionListener(listener)

Registers an object to listen for events from a component.

Signup and view all the flashcards

Component

A visual element in a GUI, like buttons or text boxes.

Signup and view all the flashcards

Pixels

A grid of small squares that make up the screen. Each square has a specific color.

Signup and view all the flashcards

getWidth() and getHeight()

The horizontal and vertical sizes of a component.

Signup and view all the flashcards

RGB Color

Color system using red, green, and blue values.

Signup and view all the flashcards

HSB Color

Color system using hue, saturation, and brightness values.

Signup and view all the flashcards

g.setColor(Color c)

Sets the current drawing color for a graphics context.

Signup and view all the flashcards

Font

Represents the size and style of text.

Signup and view all the flashcards

g.setFont(Font font)

Sets the current font for a graphics context.

Signup and view all the flashcards

g.drawString(String str, int x, int y)

Draws text using the current color and font.

Signup and view all the flashcards

g.drawLine(int x1, int y1, int x2, int y2)

Draws a line from one point to another.

Signup and view all the flashcards

g.drawRect(int x, int y, int width, int height)

Draws the outline of a rectangle.

Signup and view all the flashcards

g.fillRect(int x, int y, int width, int height)

Draws a filled-in rectangle.

Signup and view all the flashcards

Event Handling

Detect, process and react to an event.

Signup and view all the flashcards

Event Listener

Detects events that happen in order to "listen" for it.

Signup and view all the flashcards

mousePressed( MouseEvent evt )

Method for the response for pressing a mouse button.

Signup and view all the flashcards

MouseListener interface

Methods that must be implemented for mouse event listening

Signup and view all the flashcards

addMouseListener( mListener )

A method call in order to listen for events associated with a component. Must me called by the listener object.

Signup and view all the flashcards

evt.getX() and evt.getY()

Returns the coordinates of where the mouse is located on the axis.

Signup and view all the flashcards

Modifier keys

When detected this event tells that you can hold down other various other keys for different events to occur.

Signup and view all the flashcards

Dragging

When dragging occurs the user moves the while holding down the mouse button.

Signup and view all the flashcards

MouseMotionListener

Responds to the MouseMotionEvents

Signup and view all the flashcards

mouseDragged( MouseEvent evt )

Is called when it is moved with a button on the mouse being pressed.

Signup and view all the flashcards

mouseMoved( MouseEvent evt )

if the mouse is moved while a button is not pressed than the MouseMotionEvent is called

Signup and view all the flashcards

Study Notes

  • There are two basic types of GUI programs in Java: stand-alone applications and applets.

Applets

  • An applet runs in a rectangular area on a Web page.
  • Were responsible for a lot of the initial excitement about Java when it was introduced.
  • Can do things that could not otherwise be done on Web pages.
  • Applets are no longer the main focus of interest in Java.
  • Still some things that can be done best with applets, and they are still somewhat common on the Web.

Stand-alone application

  • A program that runs on its own, without depending on a Web browser.
  • Any class that has a main() routine defines a stand-alone application.
  • Until now have been "command-line" programs.
  • A GUI program offers a richer type of user interface, where the user uses a mouse and keyboard to interact with GUI components.
  • The main routine of a GUI program creates one or more components and displays them on the computer screen.
  • Once created, a GUI component follows its own programming, telling it how to draw itself and respond to events.

Displaying a message

  • JOptionPane is used regularly to display a message to the user in a GUI program.
  • showMessageDialog() is a static method in the built-in class JOptionPane.

GUI Components

  • In a Java GUI program, each GUI component in the interface is represented by an object in the program.
  • One of the most fundamental types of component is the window.
  • Windows have many behaviors and can contain other GUI components.

JFrame

  • Java has a built-in class to represent windows.
  • The most common type is represented by the JFrame class.
  • JFrame is an independent window that can act as the main window of an application.
  • A JFrame object comes with many of the behaviors of windows already programmed in, such as a titlebar and the ability to be opened and closed.
  • A JFrame doesn't come with content, the stuff that is contained in the window.
  • Content can be added either by creating a JFrame object and then adding the content to it, or by creating a subclass of JFrame and adding the content in the constructor of that subclass.

JFrame Usage

  • Example: JFrame window = new JFrame("GUI Test"); creates a new window object with title "GUI Test".
  • Window properties can be set.
  • The content of the window can be set using window.setContentPane(content);.
  • The size of the window can be set using window.setSize(250,100);.
  • The location of the window can be set using window.setLocation(100,100);.
  • Use window.setVisible(true); to make the window visible on the screen.
  • Once the window is opened, a new thread is created to manage the graphical user interface, and that thread continues to run even after main() has finished.
  • The content that is displayed in a JFrame is called its content pane.
  • In addition to its content pane, a JFrame can also have a menu bar.
  • A basic JFrame already has a blank content pane.
  • The original blank content pane can be replaced entirely.

JPanel

  • JPanel is another of the fundamental classes in Swing.
  • The basic JPanel is just a blank rectangle.
  • A useful JPanel can be made by: adding other components to the panel; and drawing something in the panel.

JPanel Usage

  • displayPanel is used as a drawing surface.
  • content is used to contain other components
  • The paintComponent() method is called by the system when a component needs to be painted on the screen.
  • The paintComponent() method in JPanel class simply fills the panel with the panel's background color.
  • super.paintComponent(g) calls the version of paintComponent() that is defined in the superclass, JPanel.
  • g.drawString() to paint the string onto the panel.

Components and Layout

  • Java has many classes that define GUI components.
  • Before these components can appear on the screen, they must be added to a container.
  • Components that are added to a container need some way of being arranged inside the container; this is called "laying out" the components.
  • The most common technique for laying out components is to use a layout manager.
  • A layout manager is an object that implements some policy for how to arrange the components in a container.
  • Different types of layout managers implement different policies.
  • One type of layout manager is defined by the BorderLayout class.
  • The BorderLayout object tells the content panel how components that are added to the content panel will be arranged inside the panel.

Technique for setting up a GUI

  • Create a container and assign a layout manager to it.
  • Create components and add them to the container.
  • Use the container as the content pane of a window or applet.
  • A container itself is a component, so it is possible that some of the components that are added to the top-level container are themselves containers, with their own layout managers and components.

Events and Listeners

  • The structure of containers and components sets up the physical appearance of a GUI, but it doesn't say anything about how the GUI behaves.
  • GUIs are largely event-driven; that is, the program waits for events that are generated by the user's actions.
  • When an event occurs, the program responds by an event-handling method.
  • In order to program the behavior of a GUI, event-handling methods must be written to respond to the events of interest.
  • The most common technique for handling events in Java is to use event listeners.
  • A listener is an object that includes one or more event-handling methods.
  • An event is detected or generated by an object.
  • The listener has the responsibility of responding to the event.
  • The event itself is represented by a third object, which carries information about the type of event, when it occurred, and so on.

Events and Listeners Usage

  • Example: the OK button in the sample program.
  • When the user clicks the button, an event is generated.
  • The event is represented by an object belonging to the class ActionEvent.
  • The event that is generated is associated with the button; the button is the source of the event.
  • The listener object in this case is an object belonging to the class ButtonHandler.
  • ButtonHandler implements the ActionListener interface, thus, the event-handling method is named actionPerformed.
  • This method contains the code that is executed when the user clicks the button; in this case, the code is a call to System.exit(), which will terminate the program.
  • To get the event from the button to the listener object: the listener object must register itself with the button as an event listener.
  • This is done with the statement okButton.addActionListener(listener);
  • This statement tells okButton that when the user clicks the button, the ActionEvent that is generated should be sent to listener.

Technique for programming the behavior of a GUI:

  • Write classes that include event-handling methods.
  • Create objects that belong to these classes and register them as listeners with the objects that will actually detect or generate the events.
  • When an event occurs, the listener is notified, and the code that was written in one of its event-handling methods is executed.

Graphics and Painting

  • Everything on a computer screen has to be drawn there.
  • The Java API includes a range of classes and methods that are devoted to drawing.

Components

  • The physical structure of a GUI is built of components.
  • The term component refers to a visual element in a GUI.
  • In Java, GUI components are represented by objects belonging to subclasses of the class java.awt.Component.
  • Most components in the Swing GUI belong to subclasses of the class javax.swing.JComponent.
  • Every component is responsible for drawing itself.
  • A component draws its content in the method public void paintComponent(Graphics g).
  • To create a drawing surface, define a subclass of JPanel and provide a custom paintComponent() method.
  • When the time comes for the component to be drawn on the screen, the system will call its paintComponent() to do the drawing.

Graphics context

  • To do any drawing at all in Java, a graphics context is needed.
  • A graphics context is an object belonging to the class java.awt.Graphics.
  • Instance methods are provided in this class for drawing shapes, text, and images.
  • Any given Graphics object can draw to only one location.
  • The Graphics class is an abstract class, so it is impossible to create a graphics context directly, with a constructor.
  • When the paintComponent() method of a component is called by the system, the parameter to that method is a graphics context for drawing on the component.
  • Every component has an instance method called getGraphics() which returns a graphics context that can be used for drawing on the component outside its paintComponent() method.

JPanel Paint Component

  • The paintComponent() method in the JPanel class simply fills the panel with the panel's background color.
  • When defining a subclass of JPanel for use as a drawing surface, fill the panel with the background color before drawing other content onto the panel.
  • This is traditionally done with a call to super.paintComponent(g).
  • Most components do all drawing operations in their paintComponent() methods.
  • If the content of the component needs to be changed, do not call paintComponent() directly to make the change; this method is meant to be called only by the system.
  • To inform the system that the component needs to be redrawn, use the component's repaint() method.
  • repaint() to inform the system that the component needs to be redrawn.
  • The system will call the component's paintComponent() method later, as soon as it gets a chance to do so, after processing other pending events if there are any.
  • paintComponent() should be capable of redrawing the content of the component on demand.

Working with the paintComponent() method

  • To work properly, the paintComponent() method must be smart enough to correctly redraw the component at any time.
  • A program should store data in its instance variables about the state of the component.
  • The paintComponent() method should use the data in these variables to decide what to draw.
  • When the program wants to change the content of the component, it should change the values of the relevant variables and call repaint().
  • When the system calls paintComponent(), that method will use the new values of the variables and will draw the component with the desired modifications.

Coordinates

  • The screen of a computer is a grid of little squares called pixels.
  • A position in the rectangle is specified by a pair of integer coordinates, (x,y).
  • The upper left corner has coordinates (0,0).
  • The x coordinate increases from left to right, and the y coordinate increases from top to bottom.
  • For any component, you can find out the size of the rectangle that it occupies by calling the instance methods getWidth() and getHeight().
  • It's not a good idea to assume that you know the size of a component, since the size is often set by a layout manager and can even change if the component is in a window and that window is resized by the user.
  • Check the size of a component before doing any drawing on that component.

Colors

  • Java is designed to work with the RGB color system.
  • An RGB color is specified by three numbers that give the level of red, green, and blue, respectively, in the color.
  • A color in Java is an object of the class java.awt.Color.
  • Construct a new color by specifying its red, blue, and green components: Color myColor = new Color(r,g,b);
  • Can avoid constructing new colors altogether, since the Color class defines several named constants representing common colors: Color.WHITE, Color.BLACK, Color.RED, Color.GREEN, Color.BLUE, Color.CYAN, Color.MAGENTA, Color.YELLOW, Color.PINK, Color.ORANGE, Color.LIGHT_GRAY, Color.GRAY, and Color.DARK_GRAY.
  • An alternative to RGB is the HSB color system: a color is specified by three numbers called the hue, the saturation, and the brightness.

HSB System

  • In Java, the hue, saturation and brightness are always specified by values of type float in the range from 0.0F to 1.0F.
  • The Color class has a static member function named getHSBColor for creating HSB colors
  • Example: Color myColor = Color.getHSBColor(h,s,b);
  • The RGB system and the HSB system are just different ways of describing the same set of colors.
  • It is possible to translate between one system and the other.

Graphics object

  • One of the properties of a Graphics object is the current drawing color, which is used for all drawing of shapes and text.
  • If g is a graphics context, change the current drawing color for g using the method g.setColor(c), where c is a Color.
  • The graphics context continues to use the color until you explicitly change it with another setColor() command.
  • If you want to know what the current drawing color is, you can call the function g.getColor(), which returns an object of type Color.
  • Every component has an associated foreground color and background color.
  • The foreground and background colors can be set by instance methods setForeground(c) and setBackground(c).

Fonts

  • A font represents a particular size and style of text.
  • In Java, a font is characterized by a font name, a style, and a size.
  • "Serif", "SansSerif", "Monospaced", and "Dialog" can always be used as font names.
  • The style of a font is specified using named constants that are defined in the Font class: Font.PLAIN, Font.ITALIC, Font.BOLD, or Font.BOLD + Font.ITALIC.
  • The size of a font is an integer.
  • Java uses the class named java.awt.Font for representing fonts.
  • Construct a new font by specifying its font name, style, and size in a constructor: Font plainFont = new Font("Serif", Font.PLAIN, 12);
  • Every graphics context has a current font, which is used for drawing text.
  • Change the current font with the setFont() method.
  • Find out the current font of g by calling the method g.getFont(), which returns an object of type Font.
  • Every component has an associated font that can be set with the instance method setFont(font).

Shapes

  • The Graphics class includes a large number of instance methods for drawing various shapes, such as lines, rectangles, and ovals.
  • The shapes are specified using the (x,y) coordinate system.
  • They are drawn in the current drawing color of the graphics context.
  • The current drawing color is set to the foreground color of the component when the graphics context is created, but it can be changed at any time using the setColor() method.
  • With all commands, any drawing that is done outside the boundaries of the component is ignored.
  • All methods are in the Graphics class, so they all must be called through an object of type Graphics.
  • drawString(String str, int x, int y) - draws the text given by the string str.
  • drawLine(int x1, int y1, int x2, int y2) - draws a line from the point (x1,y1) to the point (x2,y2).
  • drawRect(int x, int y, int width, int height) - draws the outline of a rectangle.
  • drawOval(int x, int y, int width, int height) - draws the outline of an oval.
  • drawRoundRect(int x, int y, int width, int height, int xdiam, int ydiam) - draws the outline of a rectangle with rounded corners.
  • draw3DRect(int x, int y, int width, int height, boolean raised) - draws the outline of a rectangle that is supposed to have a three-dimensional effect.
  • drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) - draws part of the oval that just fits inside the rectangle specified by x, y, width, and height.
  • fillRect(int x, int y, int width, int height) - draws a filled-in rectangle.
  • fillOval(int x, int y, int width, int height) - draws a filled-in oval.
  • fillRoundRect(int x, int y, int width, int height, int xdiam, int ydiam) - draws a filled-in rounded rectangle.
  • fill3DRect(int x, int y, int width, int height, boolean raised) - draws a filled-in three-dimensional rectangle.
  • fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) - draws a filled-in arc.

Graphics2D

  • All drawing in Java is done through an object of type Graphics.
  • The Graphics class provides basic commands and Graphics2D provides a larger set of drawing operations and is a sub-class of Graphics.
  • The graphics context given by the paintComponent() method of a JComponent actually belongs to the sub-class Graphics2D and can be type-cast to gain access to the advanced Graphics2D drawing methods.
  • Drawing in Graphics2D is based on shapes, which are objects that implement an interface named Shape.
  • Graphics2D has methods draw(Shape) and fill(Shape) for drawing the outline of a shape and for filling its interior.
  • In the Graphics class, coordinates are specified as integers and are based on pixels.
  • The shapes that are used with Graphics2D use real numbers for coordinates, and they are not necessarily bound to pixels.
  • The coordinate system can be changed and use any coordinates that are convenient to the application by applying a "transformation" to the coordinate system

Events

  • Central to programming for a graphical user interface.
  • A GUI program doesn't have a main() routine that outlines what will happen when the program is run, in a step-by-step process from beginning to end.
  • The program must be prepared to respond to events that can happen at unpredictable times and in an order that the program doesn't control.
  • The most basic kinds of events are generated by the mouse and keyboard.
  • In Java, events are represented by objects.
  • When an event occurs, the system collects all the information relevant to the event and constructs an object to contain that information.
  • Different types of events are represented by objects belonging to different classes.
  • After the event object is constructed, it is passed as a parameter to a designated method.
  • By writing that method, the programmer says what should happen when the event occurs.
  • Even though a GUI program doesn't have a main() routine, there is a sort of main routine running somewhere that executes an event loop.

Event Handling

  • For an event to have any effect, a program must detect the event and react to it.
  • In order to detect an event, the program must "listen" for it.
  • Listening for events is something that is done by an object called an event listener.
  • An event listener object must contain instance methods for handling the events for which it listens.
  • The methods that are required in a mouse event listener are specified in an interface named MouseListener.
  • To be used as a listener for mouse events, an object must implement this MouseListener interface.
  • Many events in Java are associated with GUI components.
  • Before a listener object can "hear" events associated with a given component, the listener object must be registered with the component.
  • If a MouseListener object, mListener, needs to hear mouse events associated with a Component object, comp, the listener must be registered with the component by calling comp.addMouseListener( mListener );
  • The addMouseListener() method is an instance method in class Component, and so can be used with any GUI component object.
  • The event classes and the listener interfaces are defined in the package java.awt.event.
  • Any object can act as an event listener, provided that it implements the appropriate interface.
  • Any object, a component, a panel can listen for the events that it itself generates.
  • A special class can be created just for the purpose of defining a listening object.

Steps for Event Handling

  • Put the import specification import java.awt.event.*; at the beginning of the source code.
  • Declare that some class implements the appropriate listener interface, such as MouseListener.
  • Provide definitions in that class for the methods specified by the interface.
  • Register the listener object with the component that will generate the events by calling a method such as addMouseListener() in the component.

MouseListener interface

  • Specifies five different instance methods:
    • public void mousePressed( MouseEvent evt );
    • public void mouseReleased( MouseEvent evt );
    • public void mouseClicked( MouseEvent evt );
    • public void mouseEntered( MouseEvent evt );
    • public void mouseExited( MouseEvent evt );
  • The mousePressed method is called as soon as the user presses down on one of the mouse buttons, and mouseReleased is called when the user releases a button.
  • The mouseClicked method is called if the user presses a mouse button and then releases it, without moving the mouse.
  • The mouseEntered and mouseExited methods are called when the mouse cursor enters or leaves the component.
  • The relationship between an object that generates an event and an object that responds to that event is rather loose.
  • The relationship is set up by registering one object to listen for events from the other object.
  • Each object can be developed independently, with no knowledge of the internal operation of the other object.

Mouse Coordinates

  • Often, when a mouse event occurs, you want to know the location of the mouse cursor.
  • This information is available from the MouseEvent parameter to the event-handling method, which contains instance methods that return information about the event.
  • Coordinates of the mouse cursor can be found by calling evt.getX() and evt.getY().
  • The boolean-valued instance methods evt.isShiftDown(), evt.isControlDown(), evt.isAltDown(), and evt.isMetaDown() can be called to test whether the modifier keys are pressed.
  • Pressing the right button is equivalent to holding down the Meta key while pressing the left mouse button, and pressing the middle mouse button is equivalent to holding down the ALT key.

MouseMotionListeners and Dragging

  • Whenever the mouse is moved, it generates events.
  • It is possible for a program to listen for these "mouse motion" events and respond to them.
  • The most common reason to do so is to implement dragging.
  • Dragging occurs when the user moves the mouse while holding down a mouse button.
  • The methods for responding to mouse motion events are defined in an interface named MouseMotionListener.
  • This interface specifies two event-handling methods:
    • public void mouseDragged( MouseEvent evt );
    • public void mouseMoved( MouseEvent evt );
  • The mouseDragged method is called if the mouse is moved while a button on the mouse is pressed.
  • If the mouse is moved while no mouse button is down, then mouseMoved is called instead.
  • To respond to mouse motion events, create an object that implements the MouseMotionListener interface, and you must register that object to listen for events by calling a component's addMouseMotionListener() method.
  • The dragging gesture starts when the user presses a mouse button, it continues while the mouse is dragged, and it ends when the user releases the button.
  • The programming for the response to one dragging gesture must be spread out over the three methods: mousePressed(), mouseDragged(), and mouseReleased().
  • It is necessary to set up some instance variables to keep track of what is going on between one method call and the next, such as the previous coordinates of the mouse.
  • A boolean variable, dragging, which is set to true while a dragging gesture is being processed should be implemented.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

More Like This

AJP ch1
60 questions

AJP ch1

AstonishedMookaite avatar
AstonishedMookaite
The Swing Components Challenge
3 questions

The Swing Components Challenge

AdventurousNovaculite8083 avatar
AdventurousNovaculite8083
Java GUI Components: AWT and Swing
30 questions
Use Quizgecko on...
Browser
Browser