chapter 2.2 basic gui components
TRANSCRIPT
-
7/30/2019 Chapter 2.2 Basic GUI Components
1/26
F5105 Interactive Java Programming
Chapter 2.2:-Basic GUI Components(Event Handling )
-
7/30/2019 Chapter 2.2 Basic GUI Components
2/26
Event Handling
-
7/30/2019 Chapter 2.2 Basic GUI Components
3/26
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
Object
EventObject
AWTEvent
ActionEvent
AdjustmentEvent
ItemEvent
TextEvent
ContainerEvent
FocusEvent
PaintEvent
WindowEvent
InputEvent
MouseWheelEvent
ComponentEvent
KeyEvent MouseEvent
Object
EventObject
AWTEvent
ComponentEvent
TextEvent
ItemEvent
AdjustmentEvent
ActionEvent
WindowEvent
InputEvent
MouseEventKeyEvent
MouseWheelEvent
FocusEvent
PaintEvent
ContainerEvent
-
7/30/2019 Chapter 2.2 Basic GUI Components
4/26
Event Handling Event-handling model
Three parts Event source
GUI component with which user interacts Event object
Encapsulates information about event thatoccurred
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)
-
7/30/2019 Chapter 2.2 Basic GUI Components
5/26
-
7/30/2019 Chapter 2.2 Basic GUI Components
6/26
Mouse Event Handling MouseListener and MouseMotionListener are event-
listener interfaces used for handling mouse events.
MouseListener and MouseMotionListener interfacemethods are:
public void mousePressed( MouseEvent e ) // MouseListener
called when a mouse button is pressed with the mousecursor 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
-
7/30/2019 Chapter 2.2 Basic GUI Components
7/26Lecture 7.1 Slide 7
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.
-
7/30/2019 Chapter 2.2 Basic GUI Components
8/26
Example: MouseTracker.javapublic class MouseTracker extends JFrame
implementsMouseListener , MouseMotionListener {
privateJLabel statusBar;public MouseTracker() {
statusBar = new JLabel(); // instantiate// displayed status bar at bottomgetContentPane().add( statusBar, BorderLayout.SOUTH );
// application listens to its own mouse events addMouseListener( this );addMouseMotionListener( this ); }
// MouseListener event handlers public voidmouseClicked ( MouseEvent e ) {
statusBar.setText ( "Clicked at [" +e.getX() + ", " +e.getY() + "]" );}
Note: write all MouseListener & MouseMotionListener interfaces
-
7/30/2019 Chapter 2.2 Basic GUI Components
9/26
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 event-listener 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 asimple drawing program.
-
7/30/2019 Chapter 2.2 Basic GUI Components
10/26
Fig. 12.19: Painter.javapublic class Painter extends JFrame {
private int xValue = -10, yValue = -10; // outside window
public Painter() {addMouseMotionListener( newMouseMotionAdapter () {
public voidmouseDragged ( 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
}
-
7/30/2019 Chapter 2.2 Basic GUI Components
11/26
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 methodkeyPressed , keyReleased and keyTyped each of whichrecieves 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 CapsLock and Pause).
keyTyped is called in response to pressing any otherkey on the keyboard.
-
7/30/2019 Chapter 2.2 Basic GUI Components
12/26
Fig12.22 KeyDemo.java
public class KeyDemo extends JFrame implementsKeyListener {
private String line1 = ; private JTextArea textArea;
public KeyDemo() { // allow frame to process Key events
addKeyListener( this );} // KeyDemo constructor
public voidkeyPressed ( 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
-
7/30/2019 Chapter 2.2 Basic GUI Components
13/26
Layout Manager
1. FlowLayout2. BorderLayout
3. GridLayout
-
7/30/2019 Chapter 2.2 Basic GUI Components
14/26
Layout Managers Layout managers
Provided for arranging GUI components Provide basic layout capabilities Processes layout details Programmer can concentrate on basic look and feel
-
7/30/2019 Chapter 2.2 Basic GUI Components
15/26
Layout managers
Layout manager DescriptionFlowLayout 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 aComponent and an integer index position as arguments.
BorderLayout Default for the content panes of JFrame s (and other windows) andJApplet s. Arranges the components into five areas: NORTH, SOUTH,EAST, WESTand CENTER.
GridLayout Arranges the components into rows and columns.
-
7/30/2019 Chapter 2.2 Basic GUI Components
16/26
FlowLayout Layout Manager
FlowLayout is the most basic layout manager.
GUI components are placed on a container fromleft to right in order. Class FlowLayout allowsGUI component to be left-aligned, centered (
default) and right -aligned .
-
7/30/2019 Chapter 2.2 Basic GUI Components
17/26
Example : FlowLayoutDemo.javapublic class FlowLayoutDemo extends JFrame {
private JButton left,center , right; //declaration
private Container c;privateFlowLayout layout;
public FlowLayoutDemo() {layout = new FlowLayout(); // instantiatec = getContentPane(); // get GUI components 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 componentslayout.layoutContainer( c ); } } );
c.add( center );
Center button clicked
-
7/30/2019 Chapter 2.2 Basic GUI Components
18/26
BorderLayoutLayout 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 betweencomponents
public BorderLayout( int horizontalGap, int verticalGap )
Construct a BorderLayout with horizontal componentsseparated by horizontalGap pixels and verticalcomponents separated by verticalGap pixels
-
7/30/2019 Chapter 2.2 Basic GUI Components
19/26
Example: BorderLayoutDemo.javapublic class BorderLayoutDemo extends JFrame
implements ActionListener {
private int hor=20, ver=5;privateJButton b[];private String names[] = { "Utara", "Selatan", "Timur",
"Barat", "Tengah" };privateBorderLayout 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 componentc.setLayout ( layout );
-
7/30/2019 Chapter 2.2 Basic GUI Components
20/26
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 nameb[ i ].addActionListener( this );// listen to button event
} // for
// order not importantc.add( b[ 0 ], BorderLayout.NORTH ); // North positionc.add( b[ 1 ], BorderLayout.SOUTH ); // South positionc.add( b[ 2 ], BorderLayout.EAST ); // East positionc.add( b[ 3 ], BorderLayout.WEST ); // West positionc.add( b[ 4 ], BorderLayout.CENTER ); // Center position
setSize( 300, 200 );show();
}
-
7/30/2019 Chapter 2.2 Basic GUI Components
21/26
GridLayout Layout Manager
The GridManager layout manager divides the
container into a grid so components can beplaced in rows and columns .
Each component is given the same size.
Components are added to GridLayout from top-left , preceding left-right until row is full. Thenthe process continue left-right on the next row.
-
7/30/2019 Chapter 2.2 Basic GUI Components
22/26
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 separatedvertically by v pixels
-
7/30/2019 Chapter 2.2 Basic GUI Components
23/26
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;privateGridLayout grid1, grid2;
public GridLayoutDemo() {super( "GridLayout Demo" );
grid1 = new GridLayout( 2, 3, 10, 5 );//(noOfRow, noOfCol, horGap, verGap)
grid2 = new GridLayout( 3, 2 ); //noOfRow, noOfCol,c = getContentPane();c.setLayout( grid1 );
( 2, 3, 10, 5 )
( 3, 2 )
-
7/30/2019 Chapter 2.2 Basic GUI Components
24/26
GridLayoutDemo.java
// create and add buttonsb = 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
}
-
7/30/2019 Chapter 2.2 Basic GUI Components
25/26
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.27demonstrates how JPanel can be used
to create a more complex layout for Components
-
7/30/2019 Chapter 2.2 Basic GUI Components
26/26
Example: PanelDemo.javapublic class PanelDemo extends JFrame {
privateJPanel buttonPanel; //declaration
private JButton buttons[];public PanelDemo() {
...buttonPanel = new JPanel(); //instantiatebuttons = 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}