Podcast
Questions and Answers
Which of the following best describes a stand-alone application in Java, as opposed to an applet?
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.
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?
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 ______()
.
Before a JFrame
becomes visible on the screen, its size and location are typically set using the methods setSize()
and ______()
.
Match the following GUI components with their descriptions:
Match the following GUI components with their descriptions:
Which class is commonly subclassed to create a custom drawing surface in a Java GUI?
Which class is commonly subclassed to create a custom drawing surface in a Java GUI?
The paintComponent()
method of a JPanel
should be called directly by the programmer to force a redraw of the component.
The paintComponent()
method of a JPanel
should be called directly by the programmer to force a redraw of the component.
What method is used to add a component to a container in Java GUI programming?
What method is used to add a component to a container in Java GUI programming?
A ______
is an object that implements a policy for arranging components inside a container.
A ______
is an object that implements a policy for arranging components inside a container.
Match the layout managers with their layout behaviors:
Match the layout managers with their layout behaviors:
What is the primary purpose of an event listener in Java GUI programming?
What is the primary purpose of an event listener in Java GUI programming?
An object can listen for events even if its class does not explicitly implement the corresponding listener interface.
An object can listen for events even if its class does not explicitly implement the corresponding listener interface.
What method is called to register an event listener with a component in Java?
What method is called to register an event listener with a component in Java?
The ______
interface must be implemented by a class for it to act as a listener for action events, such as button clicks.
The ______
interface must be implemented by a class for it to act as a listener for action events, such as button clicks.
Match the event listener interfaces with the corresponding event types:
Match the event listener interfaces with the corresponding event types:
Which method of the Graphics
class is used to draw a filled rectangle?
Which method of the Graphics
class is used to draw a filled rectangle?
The coordinate system in Java GUI programming has its origin (0,0) at the bottom-left corner of the component.
The coordinate system in Java GUI programming has its origin (0,0) at the bottom-left corner of the component.
What are the three components of an RGB color in Java?
What are the three components of an RGB color in Java?
The setColor()
method of a Graphics object takes a ______
object as its parameter to set the current drawing color.
The setColor()
method of a Graphics object takes a ______
object as its parameter to set the current drawing color.
Match the Font
style constants with their descriptions:
Match the Font
style constants with their descriptions:
Which method is used to change the current font of a Graphics object?
Which method is used to change the current font of a Graphics object?
The drawString()
method draws a string with the baseline of the text at the specified y-coordinate.
The drawString()
method draws a string with the baseline of the text at the specified y-coordinate.
What is the purpose of the repaint()
method in Java GUI programming?
What is the purpose of the repaint()
method in Java GUI programming?
In the HSB color model, the B
stands for ______.
In the HSB color model, the B
stands for ______.
Match the Graphics
methods with the shapes they draw:
Match the Graphics
methods with the shapes they draw:
When handling mouse events, which method is called when a mouse button is pressed and released without moving the mouse?
When handling mouse events, which method is called when a mouse button is pressed and released without moving the mouse?
Pressing the right mouse button is always equivalent to holding down the ALT key while pressing the left mouse button in Java.
Pressing the right mouse button is always equivalent to holding down the ALT key while pressing the left mouse button in Java.
What methods can be called from a MouseEvent
object to get the x and y coordinates of the mouse cursor?
What methods can be called from a MouseEvent
object to get the x and y coordinates of the mouse cursor?
To detect mouse movements while a button is pressed, you should implement the ______
interface.
To detect mouse movements while a button is pressed, you should implement the ______
interface.
Match mouse events with actions:
Match mouse events with actions:
Which of the following is NOT a valid way to specify the style of text using the Font class?
Which of the following is NOT a valid way to specify the style of text using the Font class?
Graphics2D is an interface in Java that provides advanced 2D rendering capabilities.
Graphics2D is an interface in Java that provides advanced 2D rendering capabilities.
What is the first step you should take when defining a subclass of JPanel for use as a drawing surface?
What is the first step you should take when defining a subclass of JPanel for use as a drawing surface?
The screen of a computer is essentially a grid of small squares known as ______.
The screen of a computer is essentially a grid of small squares known as ______.
Match the HSB color components with their effects.
Match the HSB color components with their effects.
Why is it generally considered bad practice to obtain a graphics context using getGraphics()
and draw directly, outside of the paintComponent()
method?
Why is it generally considered bad practice to obtain a graphics context using getGraphics()
and draw directly, outside of the paintComponent()
method?
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.
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.
When is the mouseMoved()
method called?
When is the mouseMoved()
method called?
The coordinates obtained from a MouseEvent
are expressed relative to the ______ that generated the event.
The coordinates obtained from a MouseEvent
are expressed relative to the ______ that generated the event.
Match the methods to test for modifier keys with actions:
Match the methods to test for modifier keys with actions:
Flashcards
Stand-alone Application
Stand-alone Application
A program that runs on its own, not in a web browser.
Applet
Applet
A program that runs within a rectangular area on a Web page.
main() Routine
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
GUI Component
Signup and view all the flashcards
JOptionPane.showMessageDialog()
JOptionPane.showMessageDialog()
Signup and view all the flashcards
JFrame
JFrame
Signup and view all the flashcards
JPanel
JPanel
Signup and view all the flashcards
paintComponent(Graphics g)
paintComponent(Graphics g)
Signup and view all the flashcards
Layout Manager
Layout Manager
Signup and view all the flashcards
BorderLayout
BorderLayout
Signup and view all the flashcards
Event Listener
Event Listener
Signup and view all the flashcards
actionPerformed(ActionEvent e)
actionPerformed(ActionEvent e)
Signup and view all the flashcards
addActionListener(listener)
addActionListener(listener)
Signup and view all the flashcards
Component
Component
Signup and view all the flashcards
Pixels
Pixels
Signup and view all the flashcards
getWidth() and getHeight()
getWidth() and getHeight()
Signup and view all the flashcards
RGB Color
RGB Color
Signup and view all the flashcards
HSB Color
HSB Color
Signup and view all the flashcards
g.setColor(Color c)
g.setColor(Color c)
Signup and view all the flashcards
Font
Font
Signup and view all the flashcards
g.setFont(Font font)
g.setFont(Font font)
Signup and view all the flashcards
g.drawString(String str, int x, int y)
g.drawString(String str, int x, int y)
Signup and view all the flashcards
g.drawLine(int x1, int y1, int x2, int y2)
g.drawLine(int x1, int y1, int x2, int y2)
Signup and view all the flashcards
g.drawRect(int x, int y, int width, int height)
g.drawRect(int x, int y, int width, int height)
Signup and view all the flashcards
g.fillRect(int x, int y, int width, int height)
g.fillRect(int x, int y, int width, int height)
Signup and view all the flashcards
Event Handling
Event Handling
Signup and view all the flashcards
Event Listener
Event Listener
Signup and view all the flashcards
mousePressed( MouseEvent evt )
mousePressed( MouseEvent evt )
Signup and view all the flashcards
MouseListener interface
MouseListener interface
Signup and view all the flashcards
addMouseListener( mListener )
addMouseListener( mListener )
Signup and view all the flashcards
evt.getX() and evt.getY()
evt.getX() and evt.getY()
Signup and view all the flashcards
Modifier keys
Modifier keys
Signup and view all the flashcards
Dragging
Dragging
Signup and view all the flashcards
MouseMotionListener
MouseMotionListener
Signup and view all the flashcards
mouseDragged( MouseEvent evt )
mouseDragged( MouseEvent evt )
Signup and view all the flashcards
mouseMoved( MouseEvent evt )
mouseMoved( MouseEvent evt )
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 classJOptionPane
.
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 ofJFrame
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 inJPanel
class simply fills the panel with the panel's background color. super.paintComponent(g)
calls the version ofpaintComponent()
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 theActionListener
interface, thus, the event-handling method is namedactionPerformed
.- 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, theActionEvent
that is generated should be sent tolistener
.
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 custompaintComponent()
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 itspaintComponent()
method.
JPanel Paint Component
- The
paintComponent()
method in theJPanel
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()
andgetHeight()
. - 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
, andColor.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 namedgetHSBColor
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 forg
using the methodg.setColor(c)
, wherec
is aColor
. - 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 typeColor
. - Every component has an associated foreground color and background color.
- The foreground and background colors can be set by instance methods
setForeground(c)
andsetBackground(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
, orFont.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 methodg.getFont()
, which returns an object of typeFont
. - 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 aJComponent
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)
andfill(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 ofmain
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 callingcomp.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, andmouseReleased
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
andmouseExited
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()
andevt.getY()
. - The boolean-valued instance methods
evt.isShiftDown()
,evt.isControlDown()
,evt.isAltDown()
, andevt.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'saddMouseMotionListener()
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()
, andmouseReleased()
. - 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.