OOP Week 11s
OOP Week 11s
Called when a mouse button is pressed while the mouse cursor is on a component.
pub l c vo i ouseC lcked( M ouseEventevent ) i m d i
Called when a mouse button is pressed and released while the mouse cursor remains stationary on a component.
pub l c vo i ouseR el i m d eased(M ouseEventevent )
Called when a mouse button is released after being pressed. This event is always preceded by a m ousePressed event.
pub l c vo i ouseEnt i m d ered(M ouseEventevent )
Called when the mouse cursor leaves the bounds of a component. Methods of interface M ouseM oti onLi stene r
pub l c vo i ouseD ragged( M ouseEventevent ) i m d
Called when the mouse button is pressed while the mouse cursor is on a component and the mouse is moved while the mouse button remains pressed. This event is always preceded by a call to m ousePressed. All drag events are sent to the component on which the drag began.
pub l c vo i ouseM oved(M ouseEventevent ) i m d
Called when the mouse is moved when the mouse cursor on a component. All move events are sent to the component over which the mouse is currently positioned.
3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 13.17: MouseTracker.java // Demonstrating mouse events. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MouseTracker extends JFrame implements MouseListener, MouseMotionListener { private JLabel statusBar; // set up GUI and register mouse event handlers public MouseTracker() { super( "Demonstrating Mouse Events" ); statusBar = new JLabel(); getContentPane().add( statusBar, BorderLayout.SOUTH ); addMouseListener( this ); addMouseMotionListener( this ); setSize( 275, 100 ); setVisible( true ); }
Outline
MouseTracker.ja va Lines 20-21
4
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 // MouseListener event handlers // handle event when mouse released immediately after press public void mouseClicked( MouseEvent event ) { statusBar.setText( "Clicked at [" + event.getX() + ", " + event.getY() + "]" ); } // handle event when mouse pressed public void mousePressed( MouseEvent event ) { statusBar.setText( "Pressed at [" + event.getX() + ", " + event.getY() + "]" ); } // handle event when mouse released after dragging public void mouseReleased( MouseEvent event ) { statusBar.setText( "Released at [" + event.getX() + ", " + event.getY() + "]" ); } // handle event when mouse enters area public void mouseEntered( MouseEvent event ) {
Outline
Invoked when user presses and releases mouse button MouseTracker.ja va Line 29 Invoked when user Line 36 presses mouse button Line 43 Line 50 Invoked when user releases mouse button after dragging mouse
5
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 statusBar.setText( "Mouse entered at [" + event.getX() + ", " + event.getY() + "]" ); getContentPane().setBackground( Color.GREEN ); } // handle event when mouse exits area public void mouseExited( MouseEvent event ) { statusBar.setText( "Mouse outside window" ); getContentPane().setBackground( Color.WHITE ); } // MouseMotionListener event handlers // handle event when user drags mouse with button pressed public void mouseDragged( MouseEvent event ) { statusBar.setText( "Dragged at [" + event.getX() + ", " + event.getY() + "]" ); } // handle event when user moves mouse public void mouseMoved( MouseEvent event ) { statusBar.setText( "Moved at [" + event.getX() + ", " + event.getY() + "]" ); }
Outline
MouseTracker.ja va Invoked when mouse cursor exits Line 58 JFrame Line 66 Line 73 Invoked when user drags mouse cursor
6
79 80 81 82 83 84 85 public static void main( String args[] ) { MouseTracker application = new MouseTracker(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class MouseTracker
Outline
MouseTracker.ja va
Adapter class
Implements interface Provides default implementation of each interface method Used when all methods in interface is not needed
Fig. 13.18 Event-adapter classes and the interfaces they implement in package java.awt.event
Event-adapter class Com ponent dapt A er Cont i rA dapt a ne er FocusA dapt er KeyAdapt er M ouseAdapt er M ouseM oti onA dapt er Wi ndow Adapt er
Implements interface Com ponent stener Li Cont i rLi a ne ste ne r FocusLi stener KeyLi stener M ouseLi stener M ouseM oti onLi stene r Wi ndow Li stener
9
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 13.19: Painter.java // Using class MouseMotionAdapter. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Painter extends JFrame { private int pointCount = 0; // array of 1000 java.awt.Point references private Point points[] = new Point[ 1000 ]; // set up GUI and register mouse event handler public Painter() { super( "A simple paint program" ); // create a label and place it in SOUTH of BorderLayout getContentPane().add( new JLabel( "Drag the mouse to draw" ), BorderLayout.SOUTH ); addMouseMotionListener( new MouseMotionAdapter() {
Outline
Painter.java Line 22
10
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 // store drag coordinates and repaint public void mouseDragged( MouseEvent event ) { if ( pointCount < points.length ) { points[ pointCount ] = event.getPoint(); ++pointCount; repaint(); } } } // end anonymous inner class ); // end call to addMouseMotionListener setSize( 300, 150 ); setVisible( true ); } // end Painter constructor // draw oval in a 4-by-4 bounding box at specified location on window public void paint( Graphics g ) { super.paint( g ); // clears drawing area for ( int i = 0; i < points.length && points[ i ] != null; i++ ) g.fillOval( points[ i ].x, points[ i ].y, 4, 4 ); }
Store coordinates where mouse was Line 27 dragged, then repaint JFrame
Line 30 Line 51
11
53 54 55 56 57 58 59 60
Outline
public static void main( String args[] ) { Painter application = new Painter(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class Painter
Painter.java
12
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 13.20: MouseDetails.java // Demonstrating mouse clicks and distinguishing between mouse buttons. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MouseDetails extends JFrame { private int xPos, yPos; // set title bar String; register mouse listener; size and show window public MouseDetails() { super( "Mouse clicks and buttons" ); addMouseListener( new MouseClickHandler() ); setSize( 350, 150 ); setVisible( true ); } // draw String at location where mouse was clicked public void paint( Graphics g ) { // call superclass paint method super.paint( g );
Outline
MouseDetails.ja va Line 15
13
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 g.drawString( "Clicked @ [" + xPos + ", " + yPos + "]", xPos, yPos ); } public static void main( String args[] ) { MouseDetails application = new MouseDetails(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } // inner class to handle mouse events private class MouseClickHandler extends MouseAdapter {
Outline
MouseDetails.ja va Line 41
Lines 43-44 Invoke method mouseClicked when user clicks mouse Line 46
// handle mouse click event and determine which button was pressed Line 48 public void mouseClicked( MouseEvent event ) Store mouse-cursor coordinates { where mouse was clicked xPos = event.getX(); Determine Line 51 of number yPos = event.getY(); String title = "Clicked " + event.getClickCount() + " time(s)"; if ( event.isMetaDown() ) // right mouse button title += " with right mouse button"; else if ( event.isAltDown() ) // middle mouse button title += " with center mouse button";
Determine if user clicked right mouse button Determine if user clicked middle mouse button
14
53 54 55 56 57 58 59 60 61 62 63 64
Outline
else // left mouse button title += " with left mouse button"; setTitle( title ); repaint(); // set title bar of window
MouseDetails.ja va
} // end method mouseClicked } // end private inner class MouseClickHandler } // end class MouseDetails
15
Many of the event-listener interfaces provide multiple methods. It is not always desirable to define every method in an event-listener interface. An adapter class provides this facility. An adapter class implements an interface and provides a default implementation (with an empty method body) of every method in the interface. The programmer can extend the adapter class to inherit the default implementation and then override the method(s) needed for event handling.
UTM-Java Event Handling
16
Fig. 13.21 InputEvent methods that help distinguish among left-, center- and right-mouse-button clicks
I nputEvent method
i e t ow n() sM aD
Description
Returns true when the user clicks the right mouse button on a mouse with two or three buttons. To simulate a right-mouse-button click on a one-button mouse, the user can hold down the Meta key on the keyboard and click the mouse button. Returns true when the user clicks the middle mouse button on a mouse with three buttons. To simulate a middle-mouse-button click on a one- or two-button mouse, the user can press the Alt key on the keyboard and click the only- or left-mouse button, respectively.
i l ow n() sA tD
17
Interface KeyListener
Handles key events
Generated when keys on keyboard are pressed and released KeyEvent Contains virtual key code that represents key
18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 13.22: KeyDemo.java // Demonstrating keystroke events. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class KeyDemo extends JFrame implements KeyListener { private String line1 = "", line2 = "", line3 = ""; private JTextArea textArea; // set up GUI public KeyDemo() { super( "Demonstrating Keystroke Events" ); // set up JTextArea textArea = new JTextArea( 10, 15 ); textArea.setText( "Press any key on the keyboard..." ); textArea.setEnabled( false ); textArea.setDisabledTextColor( Color.BLACK ); getContentPane().add( textArea ); addKeyListener( this ); setSize( 350, 100 ); setVisible( true );
Outline
KeyDemo.java Line 23
19
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
Outline
} // end KeyDemo constructor // handle press of any key public void keyPressed( KeyEvent event ) Called when { line1 = "Key pressed: " + event.getKeyText( event.getKeyCode() ); setLines2and3( event ); } // handle release of any key Called when public void keyReleased( KeyEvent event ) { line1 = "Key released: " + event.getKeyText( event.getKeyCode() ); setLines2and3( event ); } // handle press of an action key public void keyTyped( KeyEvent event ) { line1 = "Key typed: " + event.getKeyChar(); setLines2and3( event ); } // set second and third lines of output private void setLines2and3( KeyEvent event ) {
Line 33 and 40 Return virtual key code Line key user releases38 Line 45
20
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 line2 = "This key is " + ( event.isActionKey() ? "" : "not " ) + "an action key"; String temp = event.getKeyModifiersText( event.getModifiers() ); line3 = "Modifier keys pressed: " + ( temp.equals( "" ) ? "none" : temp );
Outline
KeyDemo.java
textArea.setText( line1 + "\n" + line2 + "\n" + line3 + "\n" ); } public static void main( String args[] ) { KeyDemo application = new KeyDemo(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class KeyDemo
Line 57 Determine if modifier keys (e.g., Alt, Ctrl, Meta and Shift) were used
21
Outline
KeyDemo.java
22
Layout managers
Provided for arranging GUI components Provide basic layout capabilities Processes layout details Programmer can concentrate on basic look and feel Interface LayoutManager
23
Description
Default for j ava . t. pp l, t aw A ej ava. t Panel aw . and j avax. i J sw ng. Panel . Places components sequentially (left to right) in the order they were added. It is also possible to specify the order of the components by using the C ont nermethod add, which takes a ai C om ponent and an integer index position as arguments. Default for the content panes of J Fram e (and other windows) and s J ppl s. Arranges the components into five areas: N O R TH , SO U TH, A et EA ST, W EST and C EN TER. Arranges the components into rows and columns.
BorderLayout
G ri dLayout
24
13.15.1 FlowLayout
FlowLayout
Most basic layout manager GUI components placed in container from left to right
25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 13.24: FlowLayoutDemo.java // Demonstrating FlowLayout alignments. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class FlowLayoutDemo extends JFrame { private JButton leftButton, centerButton, rightButton; private Container container; private FlowLayout layout; // set up GUI and register button listeners public FlowLayoutDemo() { super( "FlowLayout Demo" ); layout = new FlowLayout(); // get content pane and set its layout container = getContentPane(); container.setLayout( layout ); // set up leftButton and register listener leftButton = new JButton( "Left" ); container.add( leftButton );
Outline
FlowLayoutDemo. java Lines 17 and 21
26
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 leftButton.addActionListener( new ActionListener() { // anonymous inner class
Outline
FlowLayoutDemo. java Line 33 Line 53 When user presses left JButton, left align components
// process leftButton event public void actionPerformed( ActionEvent event ) { layout.setAlignment( FlowLayout.LEFT ); // realign attached components layout.layoutContainer( container ); } } // end anonymous inner class ); // end call to addActionListener // set up centerButton and register listener centerButton = new JButton( "Center" ); container.add( centerButton ); centerButton.addActionListener( new ActionListener() { // anonymous inner class
// process centerButton event public void actionPerformed( ActionEvent event ) { layout.setAlignment( FlowLayout.CENTER );
27
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 // realign attached components layout.layoutContainer( container ); } } ); // set up rightButton and register listener rightButton = new JButton( "Right" ); container.add( rightButton ); rightButton.addActionListener( new ActionListener() { // anonymous inner class
Outline
FlowLayoutDemo. java Line 71
// process rightButton event public void actionPerformed( ActionEvent event ) { layout.setAlignment( FlowLayout.RIGHT ); // realign attached components layout.layoutContainer( container ); } } ); setSize( 300, 75 ); setVisible( true );
28
81 82 83 84 85 86 87 88 89 90
Outline
} // end constructor FlowLayoutDemo public static void main( String args[] ) { FlowLayoutDemo application = new FlowLayoutDemo(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class FlowLayoutDemo
FlowLayoutDemo. java
29
13.15.2 BorderLayout
BorderLayout
Arranges components into five regions
NORTH SOUTH EAST WEST CENTER (top of container) (bottom of container) (left of container) (right of container) (center of container)
30
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 13.25: BorderLayoutDemo.java // Demonstrating BorderLayout. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class BorderLayoutDemo extends JFrame implements ActionListener { private JButton buttons[]; private final String names[] = { "Hide North", "Hide South", "Hide East", "Hide West", "Hide Center" }; private BorderLayout layout; // set up GUI and event handling public BorderLayoutDemo() { super( "BorderLayout Demo" ); layout = new BorderLayout( 5, 5 ); // 5 pixel gaps // get content pane and set its layout Container container = getContentPane(); container.setLayout( layout ); // instantiate button objects buttons = new JButton[ names.length ];
Outline
BorderLayoutDem o.java Lines 18 and 22
31
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 for ( int count = 0; count < names.length; count++ ) { buttons[ count ] = new JButton( names[ count ] ); buttons[ count ].addActionListener( this ); } // place buttons in BorderLayout; order not important container.add( buttons[ 0 ], BorderLayout.NORTH ); container.add( buttons[ 1 ], BorderLayout.SOUTH ); container.add( buttons[ 2 ], BorderLayout.EAST ); container.add( buttons[ 3 ], BorderLayout.WEST ); container.add( buttons[ 4 ], BorderLayout.CENTER ); setSize( 300, 200 ); setVisible( true ); } // end constructor BorderLayoutDemo // handle button events public void actionPerformed( ActionEvent event ) { for ( int count = 0; count < buttons.length; count++ ) if ( event.getSource() == buttons[ count ] ) buttons[ count ].setVisible( false ); else buttons[ count ].setVisible( true );
Outline
BorderLayoutDem o.java Lines 33-37 Place JButtons in regions specified by BorderLayout Lines 50 and 52
When JButtons are invisible, they are not displayed on screen, and BorderLayout rearranges
32
53 54 55 56 57 58 59 60 61 62 63 64
Outline
// re-layout the content pane layout.layoutContainer( getContentPane() ); } public static void main( String args[] ) { BorderLayoutDemo application = new BorderLayoutDemo(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class BorderLayoutDemo
BorderLayoutDem o.java
33
Outline
BorderLayoutDem o.java
34
13.15.3 GridLayout
GridLayout
Divides container into grid of specified row an columns Components are added starting at top-left cell
Proceed left-to-fight until row is full
35
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 13.26: GridLayoutDemo.java // Demonstrating GridLayout. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GridLayoutDemo extends JFrame implements ActionListener { private JButton buttons[]; private final String names[] = { "one", "two", "three", "four", "five", "six" }; private boolean toggle = true; private Container container; private GridLayout grid1, grid2; // set up GUI public GridLayoutDemo() { super( "GridLayout Demo" ); // set up layouts grid1 = new GridLayout( 2, 3, 5, 5 ); grid2 = new GridLayout( 3, 2 ); // get content pane and set its layout container = getContentPane(); container.setLayout( grid1 );
Outline
GridLayoutDemo. java Line 21 Line 22
Create GridLayout grid1 with 2 rows and 3 columns Create GridLayout grid2 with 3 rows and 2 columns
36
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
Outline
// create and add buttons buttons = new JButton[ names.length ]; for ( int count = buttons[ count buttons[ count container.add( } 0; count < names.length; count++ ) { ] = new JButton( names[ count ] ); ].addActionListener( this ); buttons[ count ] );
setSize( 300, 150 ); setVisible( true ); } // end constructor GridLayoutDemo // handle button events by toggling between layouts public void actionPerformed( ActionEvent event ) { Toggle current if ( toggle ) GridLayout when container.setLayout( grid2 ); user presses JButton else container.setLayout( grid1 ); toggle = !toggle; // set toggle to opposite value container.validate(); }
37
53 54 55 56 57 58 59 60
Outline
public static void main( String args[] ) { GridLayoutDemo application = new GridLayoutDemo(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class GridLayoutDemo
GridLayoutDemo. java
38
13.16 Panels
Panel
Helps organize components Class JPanel is JComponent subclass May have components (and other panels) added to them
39
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 13.27: PanelDemo.java // Using a JPanel to help lay out components. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PanelDemo extends JFrame { private JPanel buttonPanel; private JButton buttons[]; // set up GUI public PanelDemo() { super( "Panel Demo" ); // get content pane Container container = getContentPane(); // create buttons array buttons = new JButton[ 5 ]; // set up panel and set its layout Create JPanel buttonPanel = new JPanel(); buttonPanel.setLayout( new GridLayout( 1, buttons.length ) );
Outline
PanelDemo.java Line 23
to hold JButtons
40
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 // create and add buttons for ( int count = 0; count < buttons.length; count++ ) { buttons[ count ] = new JButton( "Button " + ( count + 1 ) ); buttonPanel.add( buttons[ count ] ); Add } container.add( buttonPanel, BorderLayout.SOUTH ); setSize( 425, 150 ); setVisible( true ); } // end constructor PanelDemo public static void main( String args[] ) { PanelDemo application = new PanelDemo(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class PanelDemo
Outline
JButtons to JPanel PanelDemo.java Line 29