java - mouse, keyboard, layoutsww2.cs.fsu.edu/~thrasher/cop3252/lectures/lec17.pdfthe...
TRANSCRIPT
Summer 2019
MOUSE, KEYBOARD, AND LAYOUTS
MOUSE EVENTS
• There are a few classes that are used when dealing with the mouse, the first of these is
the class representing events
• MouseEvent – the event class triggered when a mouse action occurs in a component
• Has a number of useful methods. Some examples:
• getButton() – returns which button has changed state
• getLocationOnScreen() – returns the absolute x, y position of the mouse
event, as a Point
• getPoint() – returns the x, y position relative to the source component
• getX() and getY() – returns x and y coordinates of the event relative to the
component
• getModifiersEx() – returns an integer representing modifiers pressed during
the event
SOME MOUSE EVENT CONSTANTS
• Some constants used by the methods mentioned in the previous slide:
• MouseEvent.BUTTON1, MouseEvent.BUTTON2, MouseEvent.BUTTON3
used by getButton()
• MouseEvent.MOUSE_CLICKED, MouseEvent.MOUSE_PRESSED,
MouseEvent.MOUSE_WHEEL and others are used by getModifiersEx()
SWING UTILITIES
• There are a few methods that are very useful for the mouse in the Swing Utilities class
• SwingUtilities.IsLeftMouseButton(MouseEvent)
• SwingUtilities.IsRightMouseButton(MouseEvent)
• SwingUtilities.IsMiddleMouseButton(MouseEvent)
• These detect which mouse button is being pushed in a given event
MOUSE LISTENER
• MouseListener – and interface that listens for 5 MouseEvents, contains 5 methods
• mouseClicked(MouseEvent e) – When the mouse has been clicked
(pressed and released) on a component
• mouseEntered(MouseEvent e) – When the mouse enters the component
• mouseExited(MouseEvent e) – When the mouse exits the component
• mousePressed(MouseEvent e) – When the mouse has been pressed
• mouseReleased(MouseEvent e) – When a mouse button has been released
MOUSE MOTION
• MouseMotionListener – interface that implements 2 methods to listen for mouse
events involving motion
• mouseDragged(MouseEvent e) – When a button is pressed on a component
and the mouse is moved while the button is still pressed
• mouseMoved(MouseEvent e) – When the mouse is on a component and
moving, but no buttons are pressed
MOUSE WHEEL
• MouseWheelListener – interface that implements a single method, listening for the mouse wheel to move• mouseWheelMoved(MouseWheelEvent e) – when the mouse wheel is rotated
• MouseWheelEvent – Event that fires when the mouse wheel is rotated (inherits from MouseEvent), implements some new methods• double getPreciseWheelRotation() – number of “clicks” the wheel was
rotated• int getWheelRotation() – same as previous, but integer• int getScrollAmount() – number of units that should be scrolled per click of a
mouse wheel rotation• int getScrollType() – type of scrolling that should happen, either
MouseWheelEvent.WHEEL_BLOCK_SCROLL (like scrolling with page up/down keys) or MouseWheelEvent.WHEEL_UNIT_SCROLL (like scrolling with the arrow keys)
• int getUnitsToScroll() – number of units to scroll if scroll type is MouseWheelEvent.WHEEL_UNIT_SCROLL
MOUSE ADAPTER CLASSES
• There are also two convenience classes that can be inherited from if you don’t want to
use all of the methods in a given listener class for the mouse
• MouseAdapter – implements all of the MouseListener methods as empty method
stubs
• MouseMotionAdapter – implements all of the MouseMotionListener methods
as empty method stubs
• To use these, inherit from them using extends and only implement the methods you
wish to use
MOUSE EXAMPLES
• Here is an example implementing the listeners to track the mouse
• Here is an example extending the adapter class. This uses an old method for detecting
left/right/middle mouse button that does not always work properly. An updated version of
the MouseDetailsFrame.java file can be found here
• An example of drawing using the mouse and a motion adapter
KEYBOARD
• Keyboard events are registered using the KeyEvent type and the KeyListener
interface
• KeyListener – an interface that listens for keyboard events, there are three methods
that are triggered when pressing and releasing a key
• keyPressed(KeyEvent e) – whenever a key is pressed (happens first)
• keyTyped(KeyEvent e) – whenever a key is being held down AND a valid
Unicode character could be generated (happens second)
• keyReleased(KeyEvent e) – whenever a key is released (happens last)
KEYBOARD EVENTS
• KeyEvent – event type for dealing with keyboard input. Some of the important
methods:
• char getKeyChar() – returns the character associated with the key
• int getKeyCode() – returns the key code associated with the key
• int getExtendedKeyCode() – returns an extended key code (associated
with keyboard layout) for the key
• static int getExtendedKeyCodeForChar(int c) – pass in a
character, get the extended key code
• String getKeyText(int keyCode) – returns text describing the keycode
• int getModifiersEx() – inherited from InputEvent, gets the extended
modifiers mask for this event
• boolean isActionKey() – is the key an “action” key
• isAltDown(), isControlDown(), isShiftDown() – Booleans inherited
from InputEvent, checks whether the appropriate key is down
KEYBOARD CONSTANTS
• Most keys on the keyboard (and some that are only on certain keyboard layouts) have a constant representing it in the KeyEvent class, these start with “VK”
• Some examples: VK_0, VK_M, VK_ESCAPE, VK_EQUALS, VK_NUMPAD8,
VK_JAPANESE_KATAKANA, VK_WINDOWS
• There is a constant for when a key pressed or released event doesn’t map to a proper Unicode character: CHAR_UNDEFINED
• There are also constants representing the different key events: KEY_PRESSED,
KEY_RELEASED, KEY_TYPED
KEYBOARD LISTENER
• Example - This example uses a couple of deprecated methods (getModifiers() and
getKeyModifiersText()) which should be replaced with the new extended
versions inherited from InputEvent (getModifiersEx() and
getKeyModifiersTextEx())
LAYOUT
• When adding things to a Container in Java, they can be added automatically to
appropriate positions just using the add() method.
• When resizing or adding more items, the position of such objects can move
• The actual method of positioning these objects is given by a particular layout manager
• LayoutManager – an interface implemented by classes that know how to lay out
containers
• We will discuss a few of these (there are others that exist)
• You create a new object of a type that implements this interface, then add it to the Container using setLayout(Layout l)
• Note: Similar to how you sometimes must use repaint() to tell Java to perform the
paint operations again, you can use revalidate() to tell Java to recalculate the
layout of the called component (sometimes you must use both)
FLOW LAYOUT
• Flow layouts arrange components directionally, like lines of text in a paragraph, and are of class FlowLayout
• By default, most containers use a flow layout
• FlowLayout – some useful methods
• Besides default constructor, also has 2 parameterized constructors. One takes an
integer constant for the alignment, the other takes that integer, plus two more
integers for the horizontal and vertical gaps between components
• setAlignment(int align) – sets the alignment of the layout
• setHgap(int hgap) and setVgap(int vgap) – set the horizontal and
vertical gap between components
• setAlignOnBaseline(Boolean alignOnBaseline) – whether
components should be vertically aligned at baseline
FLOW LAYOUT
• The direction the flow layout flows is actually set by the container it is in (using the container’s setComponentOrientation() method). Could be one of these values:• ComponentOrientation.LEFT_TO_RIGHT
• ComponentOrientation.RIGHT_TO_LEFT
• The align property of the flow layout (can be passed to constructor or set using a method) can be one of five values:
• FlowLayout.CENTER – each row should be centered
• FlowLayout.LEFT – each row should be left-justified
• FlowLayout.RIGHT – each row should be right-justified
• FlowLayout.LEADING – each row should be justified to leading edge, based on component orientation
• FlowLayout.TRAILING – each row should be justified to the trailing edge, based on component orientation
• Example of a flow layout
BORDER LAYOUT
• A border layout arranges components so that they fit into five different regions, each
labeled by a constant
• BorderLayout.NORTH, BorderLayout.SOUTH, BorderLayout.EAST,
BorderLayout.WEST, BorderLayout.CENTER
• When a container has a border layout, you actually use an overridden version of the add() method which takes in a second parameter, which is one of these constants
• If you don’t put a second parameter, it defaults to center
BORDER LAYOUT
• BorderLayout – class that causes a container to use a border layout
• Set horizontal and vertical gap between components the same as in FlowLayout
• In addition to constants mentioned in previous slide, also contains four relative
positioning constants which depend on the container’s component orientation
• Listed conversions are for ComponentOrientation.LEFT_TO_RIGHT
• BorderLayout.PAGE_START = BorderLayout.NORTH
• BorderLayout.PAGE_END = BorderLayout.SOUTH
• BorderLayout.LINE_START = BorderLayout.WEST
• BorderLayout.LINE_END = BorderLayout.EAST
• Example of border layout
GRID LAYOUT
• A grid layout divides the container into equal-sized rectangles and places one component
into each rectangle
• Remember, since containers are themselves considered components, you can place a
container that contains multiple components into each grid rectangle
• The order these are filled is based on the container’s component orientation
• You can set both rows and columns, but if both are non-zero, then the columns value is
ignored and the number of columns is chosen based on the number of rows and number
of components
GRID LAYOUT
• GridLayout – class that places a container’s components in a grid layout
• 3 Constructors: Default constructor, 2-parameter constructor (rows, columns), and a
4-parameter constructor (rows, columns, hgap, vgap)
• Can set gaps between components as in other layouts
• Also has setRows(int rows) and setColumns(int cols) to set the
number of rows and columns via methods
• Example of grid layout
BOX LAYOUT
• A box layout lets you choose to allow multiple components either vertically or horizontally.
• You can nest these to provide more complex effects (e.g. you can have a box layout
containing 3 panels arranged horizontally that each contain some components arranged
vertically to give a 3 column look)
• In a box layout, the components don’t wrap, so resizing will keep the components either
vertically or horizontally aligned, depending on the box
• Depending on the axis the layout is based on, components are always arranged in the
same order they were added to the container
• If on a horizontal axis, attempts to arrange components at their preferred widths and will
attempt to make all components as high as the highest component (if not possible will
align based on Y alignment, usually vertical center)
• If on a vertical axis, attempts to arrange components at their preferred heights and tries to
make all components as wide as the widest components
BOX LAYOUT
• When specifying which axis the layout will use, there are four choices defined as
constants
• BoxLayout.X_AXIS – horizontal, left-to-right
• BoxLayout.Y_AXIS – vertical, top-to-bottom
• BoxLayout.LINE_AXIS – laid out the way words are laid out in a line of text,
based on the container’s component orientation (may be horizontal left -to-right,
horizontal right-to-left, or vertical top-to-bottom)
• BoxLayout.PAGE_AXIS – the way text lines are laid out on a page based on
the container’s component orientation (same options as line axis)
• Class BoxLayout has a single constructor with 2 parameters (Container target
and int axis), but there are easier ways to create this type of layout
BOXES
• Instead of using a BoxLayout object, people often use class Box
• Class Box is a lightweight container that uses a BoxLayout object as its layout manager
• Box has a single constructor which just takes in the axis
• Has a number of helpful static methods relating to creating boxes or invisible components
to help with placement
• createHorizontalBox() and createVerticalBox() create new objects of
type Box that are on the horizontal or vertical axis and returns the new object
• createGlue(), createHorizontalGlue(), and createVerticalGlue()
create invisible “glue” components that are useful when all visible components have a
minimum width or height. Forces empty space to go between two components, instead of
to the right/below of all components.
• createHorizontalStrut(int width) and createVerticalStrut(int
height) create invisible fixed-width or fixed-height components for placement
• createRigidArea(Dimension d) creates an invisible component that is always
of size d
EXAMPLES
• Example of using a Box to hold TextAreas
• Example of using nested objects of type Box
• Example of using features of BoxLayout
• Example of combining layouts
GRID BAG LAYOUT
• One of the most flexible (and complex) layout managers in Java
• Places components in a grid of rows and columns, but allows components to take up multiple rows or columns and not everything has to be of the same size
• Contained in class GridBagLayout
• Each component added to a GridBagLayout is associated with a GridBagConstraints
• This gives rules the layout uses when placing components, component-specific
• You can reuse a GridBagConstraints object for multiple components, but if you wish them to have different constraints, it is sometimes better to have a separate constraints object for each component
• There are two ways to add constraints for components in this layout
• Use the GridBagLayout method setConstraints(Component c, GridBagConstraints constraints) and then add the component
• Alternatively, you can use an overridden version of the add() method in the container which takes in the Component and the GridBagConstraints
GRID BAG CONSTRAINTS
• You directly set these values on the GridBagConstraints instance before passing it to a component
• gridx, gridy – the row and column at the upper left of the component. Default is GridBagConstraints.RELATIVE which indicates to place it to the right (for x) or below (for y) the previous added component
• gridheight, gridwidth– number of rows and columns this object takes up. Default is 1
• ipadx, ipady – internal padding. Default is 0
• insets – external padding. Default is no padding
• fill – if the display area is larger than the component, how should it be resized. Default is GridBagConstraints.NONE
• anchor – if component is smaller than display area, indicates where it is placed. Default is GridBagComponent.CENTER
• weightx, weighty – how to distribute space among columns or rows. Important for resizing. Default is 0.0 for both, which causes components to clump in the center as extra space is added to the outside. A common recommendation is to specify as values between 0.0 and 1.0.
GRID BAG EXAMPLES
• First Example
• Second Example
OTHER LAYOUTS
• Don’t forget that there are other layouts found in the Java API. These include (but are not
limited to):
• CardLayout – a layout that treats a set of components as a stack of cards, with only
one being visible at a time
• OverlayLayout – a layout that arranges components that can overlap with each other
• GroupLayout – a layout that arranges components in hierarchical groups
• SpringLayout – a complicated layout usually not built by hand, as it is more complex
than other layouts