280 likes | 418 Vues
This lecture delves into the fundamentals of building graphical user interfaces (GUIs) in Java, specifically focusing on event handling. Key topics include the implementation of MouseListener and MouseMotionListener interfaces to respond to mouse events like clicks and drags. The session also covers keyboard events through the KeyEvent class, explaining how to handle key presses, releases, and typed events. Additionally, an overview of layout managers like FlowLayout, BorderLayout, and GridLayout is provided to help manage component layout effectively across various devices.
E N D
Building GUIs in Java III A picture's worth a thousand words CS 102-02 Lecture 8-2
Agenda • Events: Interfaces and adapters • Keyboard events • Layout managers • FlowLayout • BorderLayout • GridLayout • Panels
Listening to a Mouse • Event-listening interfaces group related methods and variables together • Mouse events include: • Single clicks • Double clicks • Shift-clicking • Mouse moving & dragging
MouseListener Interface • mouseClicked(MouseEvent) • Invoked when the mouse has been clicked on a component. • mouseEntered(MouseEvent) • Invoked when the mouse enters a component. • mouseExited(MouseEvent) • Invoked when the mouse exits a component. • mousePressed(MouseEvent) • Invoked when a mouse button has been pressed on a component. • mouseReleased(MouseEvent) • Invoked when a mouse button has been released on a component.
MouseMotionListener Interface • mouseDragged(MouseEvent) • Invoked when a mouse button is pressed on a component and then dragged. • mouseMoved(MouseEvent) • Invoked when the mouse button has been moved on a component (with no buttons down).
MouseEvents • Notice that every one of the methods takes a MouseEvent • Number of mouse clicks • The x,y position of the event relative to the source component. • Is this mouse event is the popup-menu trigger event for the platform? • Translates the coordinate position of the event by x, y.
How to Use the Event Interfaces • Write a class which implements the interface; implementing means you must either: • Write definitions for all the methods • Declare the implementing class abstract • Implementing class can then be a listener • Register the listener with a component • Registered component will get events
Listeners in Action • Write a listener: public class MouseTracker extends Applet implements MouseListener, MouseMotionListener : public void mouseClicked(MouseEvent e){ setValues( "Clicked", e.getX(), e.getY() ); } • Register the listener addMouseListener( this ); addMouseMotionListener( this );
A la carte Events • What if you don't want the whole interface? • Adapter classes enable you to pick and and choose • Every event listener interface with more than one method has a corresponding adapter class
Using Event Adapters for Fun and Profit • Event adapter class has already implemented the interface for you (What do you think the method definitions look like?) • Pick the methods you really want and override them
Overriding Adapter Methods • To override a method, you must first create a subclass of the class • Next, write your own implementation of the method
Using MouseMotionAdapter Subclass the adapter class MotionHandler extends MouseMotionAdapter { private Drag dragger; public MotionHandler( Drag d ) { dragger = d; } public void mouseDragged(MouseEvent e) { dragger.setCoordinates( e.getX(), e.getY() ); } } Override the methods you want
Putting It to Work • Got the mouseDragged event, so use it public class Drag extends Applet { private int xValue = -10; private yValue = -10; public void init() { addMouseMotionListener( new MotionHandler( this ) ); } • Where's the MouseMotionListener in this picture? Our custom event handler
Keyboard Events • More to programs than the mouse • Keys have events too, you know keyPressed(KeyEvent) Invoked when a key has been pressed. keyReleased(KeyEvent) Invoked when a key has been released. keyTyped(KeyEvent) Invoked when a key has been typed.
Know Your Keys • Some keys are ordinary, run-of-the-mill keys • "A", "S", "8", "\" and so on • Other keys are calls to action • Home, PgUp, F3 • Still other keys modify keys • Ctrl, Alt, Command
Some Key Facts I • Every key on the keyboard has a unique key code • Press a key, and an event is fired • Event (a KeyEvent) contains the key code • Key code doesn't change, even if the key is modified • Key characters are unique Unicode values fired by a key or a key combination • Key can fire different key characters ('a' or 'A')
Some Key Facts II • Action keys are usually keys which don't fire Unicode characters (For example, Home) • Key character is CHAR_UNDEFINED • Key events are usually generated by users, through the AWT but • Programs can generate key events on their own • Example: Testing a TextField
Laying It On the Line • Java's really cross-platform • Small screens, big screens, PDAs • Toasters? • Graphics are different on different platforms • Use LayoutManagers to control placement and appearance of GUIs • Different LayoutManagers have different effects
How to Use a Layout Manager • Containers must lay out contained components • Set the container's layout to a desired LayoutManager • LayoutManager takes over
Go With the Flow • FlowLayout is the most basic • Place a component, add some space, place another component • Filled a row? Start another one! • Default for Panels
Different Flows • FlowLayout() • Constructs a new Flow Layout with a centered alignment and a default 5-unit horizontal and vertical gap. • FlowLayout(int) • Constructs a new Flow Layout with the specified alignment and a default 5-unit horizontal and vertical gap. • FlowLayout(int, int, int) • Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps.
FlowLayout Demo public void actionPerformed(ActionEvent e){ int align; if ( e.getSource() == left ) align = FlowLayout.LEFT; else if ( e.getSource() == center ) align = FlowLayout.CENTER; else align = FlowLayout.RIGHT; setLayout( new FlowLayout( align ) ); validate(); // re-align components }
BorderLayout • Arrange up to 5 components • North, South, East and West • Center: Allocated al the leftover space
BorderLayout in Action In the init() method: // set layout to border layout setLayout( new BorderLayout( 5, 5 ) ); : // b is an array of Buttons //order not important add( b[ 0 ], BorderLayout.NORTH ); add( b[ 1 ], BorderLayout.SOUTH ); add( b[ 2 ], BorderLayout.EAST ); add( b[ 3 ], BorderLayout.WEST ); add( b[ 4 ], BorderLayout.CENTER );
GridLayout • Arrange components in a grid • All grid cells are the same size • Control horizontal and vertical spacing • Example from Figure 10.31 // set layout to grid layout setLayout( new GridLayout( 2, 3, 5, 5 ));
Creating GridLayouts • GridLayout() • Creates a grid layout with a default of one column per component, in a single row. • GridLayout(int, int) • Creates a grid layout with the specified number of rows and columns. • GridLayout(int, int, int, int) • Creates a grid layout with the specified number of rows and columns.
Panels • Panels are Containers • Applet inherits from Panel, which is what makes an Applet a Container • Generic containers • Hierarchical layouts • Create an Applet • Create multiple Panels, each with its own layout and add Panels to Applet's layout
Building a Panel public void init(){ buttonPanel = new Panel(); buttons = new Button[ 5 ]; buttonPanel.setLayout( new GridLayout( 1, buttons.length ) ); for ( int i = 0; i < buttons.length; i++ ) { buttons[ i ] = new Button( "Button " + (i + 1) ); buttonPanel.add( buttons[ i ] ); } setLayout( new BorderLayout() ); add( buttonPanel, BorderLayout.SOUTH ); }