Sei sulla pagina 1di 26

F5105

Interactive Java Programming

Chapter 2.2:-

Basic GUI Components (Event Handling)

Event Handling

Event Handling
GUIs are event driven Generate events when user interacts with GUI e.g., moving mouse, pressing button, typing in text field, etc. Class java.awt.event
Object Object ActionEvent ActionEvent EventObject EventObject AdjustmentEvent AdjustmentEvent AWTEvent AWTEvent ItemEvent ItemEvent FocusEvent FocusEvent TextEvent TextEvent PaintEvent PaintEvent ComponentEvent ComponentEvent WindowEvent WindowEvent InputEvent InputEvent ContainerEvent ContainerEvent

KeyEvent KeyEvent

MouseEvent MouseEvent

MouseWheelEvent MouseWheelEvent

Event Handling
Event-handling model Three parts Event source GUI component with which user interacts Event object Encapsulates information about event that occurred Event listener Receives event object when notified, then responds Programmer must perform two tasks Register event listener for event source Implement event-handling method (event handler)

Event-listener interfaces of package java.awt.event

interface interface ActionListener ActionListener interface interface AdjustmentListener

AdjustmentListener
interface interface ComponentListener ComponentListener interface interface ContainerListener ContainerListener interface interface FocusListener FocusListener interface interface EventListener EventListener interface interface ItemListener ItemListener interface interface KeyListener KeyListener interface interface MouseListener MouseListener interface interface MouseMotionListener

MouseMotionListener
interface interface TextListener TextListener interface interface WindowListener

TextListener

Mouse Event Handling


MouseListener and MouseMotionListener are eventlistener interfaces used for handling mouse events. MouseListener and MouseMotionListener interface methods are:
public void mousePressed( MouseEvent e ) // MouseListener called when a mouse button is pressed with the mouse cursor on a component public void mouseClicked( MouseEvent e ) // MouseListener called when a mouse button is pressed and released on a component without moving the cursor public void mouseReleased( MouseEvent e ) // MouseListener called when a mouse button is released after being dragged

public void mouseEntered( MouseEvent e ) // MouseListener called when a mouse cursor enters the bounds of a component

public void mouseExited( MouseEvent e ) // MouseListener called when a mouse cursor leaves the bounds of a component
public void mouseDragged( MouseEvent e )// MouseMotionListener called when a mouse button is pressed and the mouse is moved. public void mouseMoved( MouseEvent e ) // MouseMotionListener called when a mouse is moved with the mouse cursor on a component.

Lecture 7.1 Slide 7

Example: MouseTracker.java
public class MouseTracker extends JFrame implements MouseListener, MouseMotionListener { private JLabel statusBar; public MouseTracker() { statusBar = new JLabel(); // instantiate // displayed status bar at bottom getContentPane().add( statusBar, BorderLayout.SOUTH ); // application listens to its own mouse events addMouseListener( this ); addMouseMotionListener( this ); } // MouseListener event handlers public void mouseClicked( MouseEvent e ) { statusBar.setText( "Clicked at [" + e.getX() + ", " + e.getY() + "]" ); } Note: write all MouseListener & MouseMotionListener interfaces

Mouse Event Adapter Classes


Many of the event-listener provide multiple methods such as the MouseListener and MouseMotionListener interfaces. It not always desirable to define every method in eventlistener interface.
For example program may only need the mouseClicked handler from interface MouseListener or mouseDragged handler from MouseMotionListsner. For this reason Java provides the event-listener adapter classes.

Fig 12.19 uses the mouseDragged event to create a simple drawing program.

Fig. 12.19: Painter.java


public class Painter extends JFrame { private int xValue = -10, yValue = -10; // outside window public Painter() { addMouseMotionListener( new MouseMotionAdapter() { public void mouseDragged( MouseEvent e ) { xValue = e.getX(); yValue = e.getY(); repaint(); } // mouseDragged } // MouseMotionAdapter ); } public void paint( Graphics g ) { g.fillOval( xValue, yValue, 4, 4 ); // draw object as fill oval }

Keyboard Event Handling


KeyListener interface is used for handling key events. Key events are generated when keys on keyboard are pressed and released. KeyListener must provide definitions for method keyPressed, keyReleased and keyTyped each of which recieves a KeyEvent as its argument. keyPressed is called in response to pressing an action key (arrow key, Home, End, Page Up, Page Down), a function key (Num Lock, print Screen, Scroll Lock Caps Lock and Pause). keyTyped is called in response to pressing any other key on the keyboard.

Fig12.22 KeyDemo.java
public class KeyDemo extends JFrame implements KeyListener { private String line1 = ; private JTextArea textArea; public KeyDemo() { // allow frame to process Key events addKeyListener( this ); } // KeyDemo constructor public void keyPressed( KeyEvent e ) { // get key code and display key text line1 = "Key pressed: " + e.getKeyText( e.getKeyCode() ); setLines2and3( e ); // programmer define method } // keyPressed method } // KeyDemo class

Layout Manager
1. FlowLayout 2. BorderLayout 3. GridLayout

Layout Managers
Layout managers Provided for arranging GUI components Provide basic layout capabilities Processes layout details Programmer can concentrate on basic look and feel

Layout managers

Layout manager FlowLayout

Description

Default for java.awt.Applet, java.awt.Panel and javax.swing.JPanel. 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 Container method add, which takes a Component and an integer index position as arguments. Default for the content panes of JFrames (and other windows) and JApplets. Arranges the components into five areas: NORTH, SOUTH, EAST, WEST and CENTER. Arranges the components into rows and columns.

BorderLayout

GridLayout

FlowLayout Layout Manager


FlowLayout is the most basic layout manager. GUI components are placed on a container from left to right in order. Class FlowLayout allows GUI component to be left-aligned, centered ( default) and right-aligned.

Example : FlowLayoutDemo.java
public class FlowLayoutDemo extends JFrame { private JButton left, center, right; //declaration private Container c; private FlowLayout layout; public FlowLayoutDemo() { layout = new FlowLayout(); // instantiate c = getContentPane(); // get GUI components Center button clicked c.setLayout( layout ); // set the contents pane layout manager center = new JButton( "Center" ); center.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { layout.setAlignment( FlowLayout.CENTER ); // re-align attached components layout.layoutContainer( c ); } } ); c.add( center );

BorderLayout Layout Manager


Borderlayout layout manager arrange components into five regions: North, South, East, West and Center. BorderLayout constructors are: public BorderLayout ()
Constructs a BorderLayout with no pixel gaps between components

public BorderLayout( int horizontalGap, int verticalGap )


Construct a BorderLayout with horizontal components separated by horizontalGap pixels and vertical components separated by verticalGap pixels

Example: BorderLayoutDemo.java
public class BorderLayoutDemo extends JFrame implements ActionListener { private int hor=20, ver=5; private JButton b[]; private String names[] = { "Utara", "Selatan", "Timur", "Barat", "Tengah" }; private BorderLayout layout;

public BorderLayoutDemo() { super( "BorderLayout Demo" ); // constructor define the border layout, // argument (hor & ver) specify no. of pixel layout = new BorderLayout( hor, ver );
Container c = getContentPane(); // get GUI component c.setLayout( layout );

BorderLayoutDemo.java
// instantiate button objects b = new JButton[ names.length ]; for ( int i = 0; i < names.length; i++ ) { b[ i ] = new JButton( names[ i ] ); // add name b[ i ].addActionListener( this ); // listen to button event } // for // order not important c.add( b[ 0 ], BorderLayout.NORTH ); // North position c.add( b[ 1 ], BorderLayout.SOUTH ); // South position c.add( b[ 2 ], BorderLayout.EAST ); // East position c.add( b[ 3 ], BorderLayout.WEST ); // West position c.add( b[ 4 ], BorderLayout.CENTER ); // Center position

setSize( 300, 200 ); show();


}

GridLayout Layout Manager


The GridManager layout manager divides the container into a grid so components can be placed in rows and columns. Each component is given the same size. Components are added to GridLayout from topleft, preceding left-right until row is full. Then the process continue left-right on the next row.

Gridlayout Constructors are:


public GridLayout ( int rowsNo, int columnsNo )

constructs a GridLayout of rowsNo number of rows and columnsNo number of columns


public GridLayout ( int rowsNo, int columnsNo, int h, int v )

constructs a GridLayout of rowsNo number of rows and columnsNo number of columns, separated horizontally by h pixels and separated vertically by v pixels

Example: GridLayoutDemo.java
public class GridLayoutDemo extends JFrame implements ActionListener { private JButton b[]; private String names[] = { "one", "two", "three", "four", "five", "six" }; private boolean toggle = true; private Container c; private GridLayout grid1, grid2; public GridLayoutDemo() { super( "GridLayout Demo" );
( 2, 3, 10, 5 )

grid1 = new GridLayout( 2, 3, 10, 5 ); //( noOfRow, noOfCol, horGap, verGap) grid2 = new GridLayout( 3, 2 ); // noOfRow, noOfCol, c = getContentPane(); c.setLayout( grid1 );

( 3, 2 )

GridLayoutDemo.java
// create and add buttons b = new JButton[ names.length ];

for (int i = 0; i < names.length; i++ ) { b[ i ] = new JButton( names[ i ] ); // add buttons name b[ i ].addActionListener( this ); // listen to button event c.add( b[ i ] ); // add button to Container c }
setSize( 300, 150 ); // set window size show(); // show window on screen }

Panel
Complex GUIs require that each component be placed in an exact location. They usually consist of multiple panels with each panels component arranged in specific layout. The Panel constructor takes no arguments

Panel are created with class JPanel


Program Fig 12.27 demonstrates how JPanel can be used to create a more complex layout for Components

Example: PanelDemo.java
public class PanelDemo extends JFrame { private JPanel buttonPanel; // declaration private JButton buttons[]; public PanelDemo() { ... buttonPanel = new JPanel(); // instantiate buttons = new JButton[ 3 ]; // with 3 buttons // ( argument-- noOfRow, noOfCol) buttonPanel.setLayout( new GridLayout( 1, buttons.length ) );

for ( int i = 0; i < buttons.length; i++ ) { buttons[ i ] = new JButton( "Butang " + (i + 1) ); // assign name to button buttonPanel.add( buttons[ i ] ); // add button to buttonPanel } ... c.add( buttonPanel, BorderLayout.SOUTH ); // add buttonPanel to // Container c
}

Potrebbero piacerti anche