68
Java Java Mouse / Keyboard Mouse / Keyboard Events Events and and Layout Managers Layout Managers INE2720 INE2720 Web Application Software Web Application Software Development Development Essential Materials Essential Materials

Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

Embed Size (px)

Citation preview

Page 1: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

JavaJava – – Mouse / Keyboard Mouse / Keyboard EventsEvents and and Layout ManagersLayout Managers

INE2720INE2720

Web Application Software Web Application Software DevelopmentDevelopment

Essential MaterialsEssential Materials

Page 2: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

22

OutlineOutline

General event-handling strategyGeneral event-handling strategy Handling events with separate listenersHandling events with separate listeners Handling events by implementing interfacesHandling events by implementing interfaces Handling events with named inner classesHandling events with named inner classes Handling events with anonymous inner Handling events with anonymous inner

classesclasses The standard AWT listener typesThe standard AWT listener types Subtleties with mouse eventsSubtleties with mouse events ExamplesExamples

Page 3: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

33

General StrategyGeneral Strategy

Determine what type of listener is of interestDetermine what type of listener is of interest– 11 standard AWT listener types, described on later slide. 11 standard AWT listener types, described on later slide.

ActionListenerActionListener, AdjustmentListener, , AdjustmentListener, ComponentListenerComponentListener, , ContainerListener, ContainerListener, FocusListenerFocusListener, ItemListener, , ItemListener, KeyListenerKeyListener, , MouseListenerMouseListener, MouseMotionListener, , MouseMotionListener, TextListenerTextListener, WindowListener, WindowListener

Define a class of that typeDefine a class of that type– Implement interface (KeyListener, MouseListener, etc.)Implement interface (KeyListener, MouseListener, etc.)– Extend class (KeyAdapter, MouseAdapter, etc.)Extend class (KeyAdapter, MouseAdapter, etc.)

Register an object of your listener class with the Register an object of your listener class with the windowwindow– w.addw.addXxxXxxListener(new MyListenerClass());Listener(new MyListenerClass());

E.g., addKeyListener, addMouseListenerE.g., addKeyListener, addMouseListener

Page 4: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

44

Handling Events with a Handling Events with a Separate Listener: Simple Separate Listener: Simple CaseCase

import java.applet.Applet;import java.applet.Applet;import java.awt.*;import java.awt.*;

publicpublic class ClickReporter class ClickReporter extendsextends Applet { Applet { public void init() {public void init() { setBackground(Color.yellow);setBackground(Color.yellow); addMouseListener(new ClickListener());addMouseListener(new ClickListener()); }}}}

Listener does not need to call any methods Listener does not need to call any methods of the window to which it is attachedof the window to which it is attached

Page 5: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

55

Separate Listener: Separate Listener: Simple Case Simple Case (Continued)(Continued)

import java.awt.event.*;import java.awt.event.*;

public class ClickListener public class ClickListener extends MouseAdapterextends MouseAdapter { {

public void mousePressed(MouseEvent event) {public void mousePressed(MouseEvent event) {

System.out.println("Mouse pressed at (" +System.out.println("Mouse pressed at (" +

event.getX() + "," + event.getY() + ").");event.getX() + "," + event.getY() + ").");

}}

}}

Page 6: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

66

Generalizing Simple Generalizing Simple CaseCase What if ClickListener wants to draw a What if ClickListener wants to draw a

circle wherever mouse is clicked? circle wherever mouse is clicked? Why can’t it just call getGraphics to get a Why can’t it just call getGraphics to get a

Graphics object with which to draw?Graphics object with which to draw? General solution:General solution:

– Call event.getSource to obtain a reference to Call event.getSource to obtain a reference to window or GUI component from which event window or GUI component from which event originatedoriginated

– Cast result to type of interestCast result to type of interest– Call methods on that referenceCall methods on that reference

Page 7: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

77

Handling Events with Handling Events with Separate Listener: General Separate Listener: General CaseCaseimport java.applet.Applet;import java.applet.Applet;import java.awt.*;import java.awt.*;

publicpublic class CircleDrawer1 class CircleDrawer1 extendsextends Applet Applet {{

public void init() {public void init() { setForeground(Color.blue);setForeground(Color.blue); addMouseListener(new CircleListener());addMouseListener(new CircleListener()); }}}}

Page 8: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

88

Separate Listener: Separate Listener: General Case General Case (Continued)(Continued)

import java.applet.Applet;import java.applet.Applet;

import java.awt.*;import java.awt.*;

import java.awt.event.*;import java.awt.event.*;

publicpublic class CircleListener class CircleListener extendsextends MouseAdapter { MouseAdapter {

private int radius = 25;private int radius = 25;

public void mousePressed(MouseEvent event) {public void mousePressed(MouseEvent event) {

Applet app = (Applet)event.getSource();Applet app = (Applet)event.getSource();

Graphics g = Graphics g = appapp.getGraphics();.getGraphics();

g.fillOval(event.getX()-radius, g.fillOval(event.getX()-radius,

event.getY()-radius,event.getY()-radius,

2*radius, 2*radius);2*radius, 2*radius);

}}

}}

Page 9: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

99

Case 2: Implementing Case 2: Implementing a Listener Interfacea Listener Interfaceimport java.applet.Applet;import java.applet.Applet;import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;

public class CircleDrawer2 extends Appletpublic class CircleDrawer2 extends Applet implements MouseListenerimplements MouseListener { { private int radius = 25;private int radius = 25; public void init() {public void init() { setForeground(Color.blue);setForeground(Color.blue); addMouseListener(this);addMouseListener(this); }}

Page 10: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1010

Implementing a Implementing a Listener Interface Listener Interface (Continued)(Continued)public void public void mouseEnteredmouseEntered(MouseEvent event) {}(MouseEvent event) {}

public void public void mouseExitedmouseExited(MouseEvent event) {}(MouseEvent event) {}

public void public void mouseReleasedmouseReleased(MouseEvent event) (MouseEvent event) {}{}

public void public void mouseClickedmouseClicked(MouseEvent event) {}(MouseEvent event) {}

public void mousePressed(MouseEvent event) {public void mousePressed(MouseEvent event) {

Graphics g = getGraphics();Graphics g = getGraphics();

g.fillOval(event.getX()-radius,g.fillOval(event.getX()-radius,

event.getY()-radius,event.getY()-radius,

2*radius, 2*radius);2*radius, 2*radius);

}}

}}

Page 11: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1111

Case 3: Named Inner Case 3: Named Inner ClassesClasses

import java.applet.Applet;import java.applet.Applet;import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;

publicpublic class CircleDrawer3 class CircleDrawer3 extendsextends Applet {Applet {

public void init() {public void init() { setForeground(Color.blue);setForeground(Color.blue); addMouseListener(new addMouseListener(new

CircleListener());CircleListener()); }}

Page 12: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1212

Named Inner Classes Named Inner Classes (Continued)(Continued) Note: still part of class from previous slideNote: still part of class from previous slide

private class CircleListener private class CircleListener extends extends MouseAdapterMouseAdapter { {

private int radius = 25;private int radius = 25;

public void mousePressed(MouseEvent event) {public void mousePressed(MouseEvent event) {

Graphics g = getGraphics();Graphics g = getGraphics();

g.fillOval(event.getX()-radius, event.getY()-radius,g.fillOval(event.getX()-radius, event.getY()-radius,

2*radius, 2*radius);2*radius, 2*radius);

}}

}}

}}

Page 13: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1313

Case 4: Anonymous Case 4: Anonymous Inner ClassesInner Classes

publicpublic class CircleDrawer4 class CircleDrawer4 extendsextends Applet { Applet { public void init() public void init() {{ setForeground(Color.blue);setForeground(Color.blue); addMouseListeneraddMouseListener ((new MouseAdapter() {new MouseAdapter() { private int radius = 25;private int radius = 25; public void mousePressed(MouseEvent event) {public void mousePressed(MouseEvent event) { Graphics g = getGraphics();Graphics g = getGraphics(); g.fillOval(event.getX()-radius, event.getY()-radius,g.fillOval(event.getX()-radius, event.getY()-radius, 2*radius, 2*radius);2*radius, 2*radius); }} }});); }}}}

Page 14: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1414

Event Handling Event Handling Strategies: Strategies: Pros and ConsPros and Cons Separate ListenerSeparate Listener

– AdvantagesAdvantages Can extend adapter and thus ignore unused Can extend adapter and thus ignore unused

methodsmethods Separate class easier to manageSeparate class easier to manage

– DisadvantageDisadvantage Need extra step to call methods in main windowNeed extra step to call methods in main window

Main window that implements interfaceMain window that implements interface– AdvantageAdvantage

No extra steps needed to call methods in main No extra steps needed to call methods in main windowwindow

– DisadvantageDisadvantage Must implement methods you might not care aboutMust implement methods you might not care about

Page 15: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1515

Event Handling Event Handling Strategies: Strategies: Pros and Cons, cont.Pros and Cons, cont. Named inner classNamed inner class

– AdvantagesAdvantages Can extend adapter and thus ignore unused methodsCan extend adapter and thus ignore unused methods No extra steps needed to call methods in main windowNo extra steps needed to call methods in main window

– DisadvantageDisadvantage A bit harder to understandA bit harder to understand

Anonymous inner classAnonymous inner class– AdvantagesAdvantages

Same as named inner classesSame as named inner classes Even shorterEven shorter

– DisadvantageDisadvantage Much harder to understandMuch harder to understand

Page 16: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1616

Standard AWT Event Standard AWT Event ListenersListeners(Summary)(Summary)

Adapter ClassListener (If Any) Registration Method

ActionListener addActionListener AdjustmentListener addAdjustmentListener ComponentListener ComponentAdapter addComponentListener ContainerListener ContainerAdapter addContainerListener FocusListener FocusAdapter addFocusListener ItemListener addItemListener KeyListener KeyAdapter addKeyListener MouseListener MouseAdapter addMouseListener MouseMotionListener MouseMotionAdapter addMouseMotionListener

TextListener addTextListener WindowListener WindowAdapter addWindowListener

Why no adapter class?

Page 17: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1717

Standard AWT Event Standard AWT Event ListenersListeners(Details)(Details) ActionListenerActionListener

– Handles buttons and a few other actionsHandles buttons and a few other actions actionPerformed(ActionEvent event)actionPerformed(ActionEvent event)

AdjustmentListenerAdjustmentListener– Applies to scrollingApplies to scrolling

adjustmentValueChanged(AdjustmentEvent event)adjustmentValueChanged(AdjustmentEvent event)

ComponentListenerComponentListener– Handles moving/resizing/hiding GUI objectsHandles moving/resizing/hiding GUI objects

componentResized(ComponentEvent event)componentResized(ComponentEvent event) componentMoved (ComponentEvent event)componentMoved (ComponentEvent event) componentShown(ComponentEvent event)componentShown(ComponentEvent event) componentHidden(ComponentEvent event)componentHidden(ComponentEvent event)

Page 18: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1818

Standard AWT Event Standard AWT Event ListenersListeners(Details Continued)(Details Continued) ContainerListenerContainerListener

– Triggered when window adds/removes Triggered when window adds/removes GUI controls GUI controls componentAdded(ContainerEvent event)componentAdded(ContainerEvent event) componentRemoved(ContainerEvent event)componentRemoved(ContainerEvent event)

FocusListenerFocusListener– Detects when controls get/lose Detects when controls get/lose

keyboard focuskeyboard focus focusGained(FocusEvent event)focusGained(FocusEvent event) focusLost(FocusEvent event)focusLost(FocusEvent event)

Page 19: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1919

Standard AWT Event Standard AWT Event ListenersListeners(Details Continued)(Details Continued) ItemListenerItemListener

– Handles selections in lists, checkboxes, Handles selections in lists, checkboxes, etc.etc.

itemStateChanged(ItemEvent event)itemStateChanged(ItemEvent event) KeyListenerKeyListener

– Detects keyboard eventsDetects keyboard events keyPressed(KeyEvent event)keyPressed(KeyEvent event) -- any key -- any key

pressed downpressed down keyReleased(KeyEvent event)keyReleased(KeyEvent event) -- -- any key any key

releasedreleased keyTyped(KeyEvent event)keyTyped(KeyEvent event) -- -- key for printable key for printable

char releasedchar released

Page 20: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2020

Standard AWT Event Standard AWT Event ListenersListeners(Details Continued)(Details Continued) MouseListenerMouseListener

– Applies to basic mouse eventsApplies to basic mouse events mouseEntered(MouseEvent event)mouseEntered(MouseEvent event) mouseExited(MouseEvent event)mouseExited(MouseEvent event) mousePressed(MouseEvent event)mousePressed(MouseEvent event) mouseReleased(MouseEvent event)mouseReleased(MouseEvent event) mouseClicked(MouseEvent event)mouseClicked(MouseEvent event) -- Release without -- Release without

dragdrag– Applies on release if no movement since pressApplies on release if no movement since press

MouseMotionListenerMouseMotionListener– Handles mouse movementHandles mouse movement

mouseMoved(MouseEvent event)mouseMoved(MouseEvent event) mouseDragged(MouseEvent event)mouseDragged(MouseEvent event)

Page 21: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2121

Standard AWT Event Standard AWT Event ListenersListeners(Details Continued)(Details Continued) TextListenerTextListener

– Applies to textfields and text areasApplies to textfields and text areas textValueChanged(TextEvent event)textValueChanged(TextEvent event)

WindowListenerWindowListener– Handles high-level window eventsHandles high-level window events

windowOpened, windowClosing, windowOpened, windowClosing, windowClosed, windowIconified, windowClosed, windowIconified, windowDeiconified, windowActivated, windowDeiconified, windowActivated, windowDeactivatedwindowDeactivated

– windowClosing particularly usefulwindowClosing particularly useful

Page 22: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2222

Example: Simple Example: Simple WhiteboardWhiteboard

import java.applet.Applet;import java.applet.Applet;import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;

publicpublic class SimpleWhiteboard extends Applet class SimpleWhiteboard extends Applet {{

protected int lastX=0, lastY=0;protected int lastX=0, lastY=0; public void init() {public void init() { setBackground(Color.white);setBackground(Color.white); setForeground(Color.blue);setForeground(Color.blue); addMouseListener(addMouseListener(new PositionRecorder()new PositionRecorder());); addMouseMotionListener(addMouseMotionListener(new new

LineDrawer()LineDrawer());); }} protected void record(int x, int y) {protected void record(int x, int y) { lastX = x; lastY = y;lastX = x; lastY = y; }}

Page 23: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2323

Simple Whiteboard Simple Whiteboard (Continued)(Continued)

private class private class PositionRecorderPositionRecorder extends extends MouseAdapterMouseAdapter { {

public void public void mouseEnteredmouseEntered(MouseEvent event) {(MouseEvent event) {

requestFocus(); // Plan ahead for typingrequestFocus(); // Plan ahead for typing

record(event.getX(), event.getY());record(event.getX(), event.getY());

}}

public void public void mousePressedmousePressed(MouseEvent event) {(MouseEvent event) {

record(event.getX(), event.getY());record(event.getX(), event.getY());

}}

}}

......

Page 24: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2424

Simple Whiteboard Simple Whiteboard (Continued)(Continued)

......

private class private class LineDrawerLineDrawer extends extends MouseMotionAdapterMouseMotionAdapter { {

public void public void mouseDraggedmouseDragged(MouseEvent event) {(MouseEvent event) {

int x = event.getX();int x = event.getX();

int y = event.getY();int y = event.getY();

Graphics g = getGraphics();Graphics g = getGraphics();

g.drawLine(lastX, lastY, x, y);g.drawLine(lastX, lastY, x, y);

record(x, y);record(x, y);

}}

}}

}}

Page 25: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2525

Whiteboard: Adding Whiteboard: Adding Keyboard EventsKeyboard Eventsimport java.applet.Applet;import java.applet.Applet;import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;

publicpublic class Whiteboard class Whiteboard extends extends SimpleWhiteboardSimpleWhiteboard { {

protected FontMetrics fm;protected FontMetrics fm; public void init() {public void init() { super.init();super.init(); Font font = new Font("Serif", Font.BOLD, 20);Font font = new Font("Serif", Font.BOLD, 20); setFont(font);setFont(font); fm = getFontMetrics(font);fm = getFontMetrics(font); addKeyListener(addKeyListener(new CharDrawer()new CharDrawer());); }}

Page 26: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2626

Whiteboard Whiteboard (Continued)(Continued)

......

private class private class CharDrawerCharDrawer extends KeyAdapterextends KeyAdapter { {

// When user types a printable character,// When user types a printable character,

// draw it and shift position rightwards.// draw it and shift position rightwards.

public void public void keyTypedkeyTyped(KeyEvent event) {(KeyEvent event) {

String s = String s = String.valueOf(event.getKeyChar());String.valueOf(event.getKeyChar());

getGraphics().drawString(s, lastX, lastY);getGraphics().drawString(s, lastX, lastY);

record(lastX + fm.stringWidth(s), lastY);record(lastX + fm.stringWidth(s), lastY);

}}

}}

}}

Page 27: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2727

SummarySummary

General strategyGeneral strategy– Determine what type of listener is of interestDetermine what type of listener is of interest

Check table of standard typesCheck table of standard types

– Define a class of that typeDefine a class of that type Extend adapter separately, implement interface, extend Extend adapter separately, implement interface, extend

adapter in named inner class, extend adapter in adapter in named inner class, extend adapter in anonymous inner classanonymous inner class

– Register an object of your listener class with the windowRegister an object of your listener class with the window Call addCall addXxxXxxListenerListener

Understanding listenersUnderstanding listeners– Methods give specific behavior. Methods give specific behavior.

Arguments to methods are of type XxxEventArguments to methods are of type XxxEvent– Methods in MouseEvent of particular interestMethods in MouseEvent of particular interest

Page 28: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2828

Break Time – 15 Break Time – 15 minutesminutes

Page 29: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2929

Layout Managers: Layout Managers: OutlineOutline How layout managers simplify How layout managers simplify

interface design?interface design? Standard layout managersStandard layout managers

– FlowLayoutFlowLayout, , BorderLayoutBorderLayout, , CardLayoutCardLayout, , GridLayoutGridLayout, , GridBagLayoutGridBagLayout, , BoxLayoutBoxLayout

Positioning components manuallyPositioning components manually Strategies for using layout Strategies for using layout

managers effectivelymanagers effectively Using invisible componentsUsing invisible components

Page 30: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3030

Layout ManagersLayout Managers

Page 31: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3131

Layout ManagersLayout Managers

Assigned to each ContainerAssigned to each Container– Give Give sizessizes and and positionspositions to components in the window to components in the window– Helpful for windows whose size changes or that Helpful for windows whose size changes or that

display on multiple operating systemsdisplay on multiple operating systems Relatively easy for simple layoutsRelatively easy for simple layouts

– But, it is surprisingly hard to get complex layouts with But, it is surprisingly hard to get complex layouts with a single layout managera single layout manager

Controlling complex layoutsControlling complex layouts– Use nested containers (each with its own layout Use nested containers (each with its own layout

manager)manager)– Use invisible components and layout manager optionsUse invisible components and layout manager options– Write your own layout managerWrite your own layout manager– Turn layout managers off and arrange things manuallyTurn layout managers off and arrange things manually

Page 32: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3232

FlowLayoutFlowLayout

Default layout for Default layout for PanelPanel and and AppletApplet BehaviorBehavior

– Resizes components to their Resizes components to their preferredpreferred size size– Places components in rows Places components in rows left to rightleft to right, , top to bottomtop to bottom– Rows are Rows are centeredcentered by default by default

ConstructorsConstructors– FlowLayoutFlowLayout()()

Centers each row and keeps 5 pixels between entries in a row and between Centers each row and keeps 5 pixels between entries in a row and between rowsrows

– FlowLayoutFlowLayout((int alignmentint alignment)) Same 5 pixels spacing, but changes the alignment of the rowsSame 5 pixels spacing, but changes the alignment of the rows FlowLayout.LEFT, FlowLayout.RIGHT, FlowLayout.CENTERFlowLayout.LEFT, FlowLayout.RIGHT, FlowLayout.CENTER

– FlowLayoutFlowLayout((int alignmentint alignment,, int hGapint hGap,, int vGapint vGap)) Specify the alignment as well as the horizontal and vertical spacing between Specify the alignment as well as the horizontal and vertical spacing between

componentscomponents

Page 33: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3333

FlowLayout: ExampleFlowLayout: Examplepublicpublic class FlowTest class FlowTest extendsextends Applet { Applet {

public void init() {public void init() {

// setLayout(new FlowLayout()); // setLayout(new FlowLayout()); [Default][Default]

for(int i=1; i<6; i++) {for(int i=1; i<6; i++) {

add(new Button("Button " + i));add(new Button("Button " + i));

}}

}}

}}

Page 34: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3434

BorderLayoutBorderLayout

Default layout for Default layout for FrameFrame and and DialogDialog BehaviorBehavior

– Divides the Divides the ContainerContainer into into five regionsfive regions– Each region is identified by a corresponding Each region is identified by a corresponding BorderLayoutBorderLayout constant constant

NORTHNORTH, , SOUTHSOUTH, , EASTEAST, , WESTWEST, and , and CENTERCENTER– NORTH and SOUTH NORTH and SOUTH respect the preferred heightrespect the preferred height of the of the

componentcomponent– EAST and WEST EAST and WEST respect the preferred widthrespect the preferred width of the of the

componentcomponent– CENTER is given the remaining spaceCENTER is given the remaining space

Is allowing a maximum of five components too Is allowing a maximum of five components too restrictive? Why not?restrictive? Why not?

Page 35: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3535

BorderLayout BorderLayout (Continued)(Continued) ConstructorsConstructors

– BorderLayoutBorderLayout()() Border layout with no gaps between componentsBorder layout with no gaps between components

– BorderLayoutBorderLayout(int hGap, int vGap)(int hGap, int vGap) Border layout with the specified empty pixels Border layout with the specified empty pixels

between regionsbetween regions

Adding ComponentsAdding Components– add(component, BorderLayout.add(component, BorderLayout.REGIONREGION))– Always specify the region in which to add the Always specify the region in which to add the

componentcomponent CENTER is the default, but specify it explicitly to CENTER is the default, but specify it explicitly to

avoid confusion with other layout managersavoid confusion with other layout managers

Page 36: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3636

BorderLayout: BorderLayout: ExampleExample

publicpublic class BorderTest class BorderTest extends extends Applet {Applet {

public void init() {public void init() {

setLayout(setLayout(new BorderLayout()new BorderLayout()););

add(new Button("Button 1"), add(new Button("Button 1"), BorderLayout.NORTHBorderLayout.NORTH););

add(new Button("Button 2"), add(new Button("Button 2"), BorderLayout.SOUTHBorderLayout.SOUTH););

add(new Button("Button 3"), add(new Button("Button 3"), BorderLayout.EASTBorderLayout.EAST););

add(new Button("Button 4"), add(new Button("Button 4"), BorderLayout.WESTBorderLayout.WEST););

add(new Button("Button 5"), add(new Button("Button 5"), BorderLayout.CENTERBorderLayout.CENTER););

}}

}}

Page 37: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3737

GridLayoutGridLayout

BehaviorBehavior– Divides window into Divides window into equal-sized rectanglesequal-sized rectangles based based

upon the upon the number of rows and columns specifiednumber of rows and columns specified– Items placed into cells left-to-right, top-to-bottom, Items placed into cells left-to-right, top-to-bottom,

based on the order added to the containerbased on the order added to the container– Ignores the preferred size of the component; Ignores the preferred size of the component;

each component is each component is resized to fit into its grid cellresized to fit into its grid cell– Too few components results in blank cellsToo few components results in blank cells– Too many components results in extra columnsToo many components results in extra columns

Page 38: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3838

GridLayout GridLayout (Continued)(Continued) ConstructorsConstructors

– GridLayoutGridLayout()() Creates a single row with one column allocated per Creates a single row with one column allocated per

componentcomponent

– GridLayoutGridLayout(int rows, int cols)(int rows, int cols) Divides the window into the specified number of Divides the window into the specified number of

rows and columnsrows and columns Either rows or cols (but not both) can be zeroEither rows or cols (but not both) can be zero

– GridLayoutGridLayout(int rows, int cols, (int rows, int cols, int hGap, int vGap) int hGap, int vGap)

Uses the specified gaps between cellsUses the specified gaps between cells

Page 39: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3939

GridLayout, ExampleGridLayout, Examplepublicpublic class GridTest class GridTest extends extends Applet {Applet {

public void init() {public void init() {

setLayout(setLayout(new GridLayout(2,3)new GridLayout(2,3)); // 2 rows, 3 ); // 2 rows, 3 colscols

add(new Button("Button One"));add(new Button("Button One"));

add(new Button("Button Two"));add(new Button("Button Two"));

add(new Button("Button Three"));add(new Button("Button Three"));

add(new Button("Button Four"));add(new Button("Button Four"));

add(new Button("Button Five"));add(new Button("Button Five"));

add(new Button("Button Six"));add(new Button("Button Six"));

}}

}}

Page 40: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4040

CardLayoutCardLayout

BehaviorBehavior– Stacks components on top of each other, displaying Stacks components on top of each other, displaying

the top onethe top one– Associates a name with each component in windowAssociates a name with each component in window

Panel cardPanel;Panel cardPanel;

CardLayout layout new CardLayout();CardLayout layout new CardLayout();

cardPanel.setLayout(cardPanel.setLayout(layoutlayout););

......

cardPanel.add(cardPanel.add("Card 1""Card 1", component1);, component1);

cardPanel.add(cardPanel.add("Card 2""Card 2", component2);, component2);......

layout.show(cardPanel, "Card 1");layout.show(cardPanel, "Card 1");

layout.first(cardPanel);layout.first(cardPanel);

layout.next(cardPanel);layout.next(cardPanel);

Page 41: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4141

CardLayout, ExampleCardLayout, Example

Page 42: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4242

GridBagLayoutGridBagLayout

BehaviorBehavior– Divides the window into Divides the window into gridsgrids, without requiring , without requiring

the components to be the same sizethe components to be the same size About About threethree times more flexible than the other times more flexible than the other

standard layout managers, but standard layout managers, but ninenine times harder to times harder to useuse

– Each component managed by a grid bag layout Each component managed by a grid bag layout is associated with an instance of is associated with an instance of GridBagConstraintsGridBagConstraints

The The GridBagConstraintsGridBagConstraints specifies: specifies:– How the component is laid out in the display area How the component is laid out in the display area – In which cell the component starts and endsIn which cell the component starts and ends– How the component stretches when extra room is How the component stretches when extra room is

availableavailable– Alignment in cellsAlignment in cells

Page 43: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4343

GridBagLayout: Basic GridBagLayout: Basic StepsSteps Set the layout, saving a reference to itSet the layout, saving a reference to it

GridBagLayout layout = new GridBagLayout();GridBagLayout layout = new GridBagLayout();setLayout(layout);setLayout(layout);

Allocate a Allocate a GridBagConstraintsGridBagConstraints object objectGridBagConstraints GridBagConstraints constraintsconstraints = = new GridBagConstraints();new GridBagConstraints();

Set up the Set up the GridBagConstraintsGridBagConstraints for for component 1component 1

constraints.gridxconstraints.gridx = x1; = x1;constraints.gridyconstraints.gridy = y1;= y1;constraints.gridwidthconstraints.gridwidth = width1; = width1;constraints.gridheightconstraints.gridheight = height1; = height1;

Add component 1 to the window, including constraintsAdd component 1 to the window, including constraintsadd(add(component1component1, , constraintsconstraints););

Repeat the last two steps for each remaining Repeat the last two steps for each remaining componentcomponent

Page 44: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4444

GridBagConstraintsGridBagConstraints

Copied when component added to windowCopied when component added to window Thus, can reuse the Thus, can reuse the GridBagConstraintsGridBagConstraints

GridBagConstraints GridBagConstraints constraintsconstraints = new GridBagConstraints(); = new GridBagConstraints();

constraints.constraints.gridxgridx = x1; = x1;

constraints.constraints.gridygridy = y1;= y1;

constraints.constraints.gridwidth = width1;gridwidth = width1;

constraints.constraints.gridheight = height1;gridheight = height1;

add(add(componentcomponent11, constraints);, constraints);

constraints.constraints.gridxgridx = x1; = x1;

constraints.constraints.gridygridy = y1;= y1;

add(add(componentcomponent22, constraints);, constraints);

Page 45: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4545

GridBagConstraints GridBagConstraints FieldsFields gridx, gridygridx, gridy

– Specifies the top-left corner of the componentSpecifies the top-left corner of the component– Upper left of grid is located at (gridx, Upper left of grid is located at (gridx,

gridy)=(0,0)gridy)=(0,0)– Set to Set to GridBagConstraints.RELATIVEGridBagConstraints.RELATIVE to to

auto-increment row/columnauto-increment row/column

GridBagConstraints constraints = new GridBagConstraints constraints = new GridBagConstraints();GridBagConstraints();

constraints.constraints.gridxgridx = = GridBagConstraints.RELATIVEGridBagConstraints.RELATIVE;;

containercontainer.add(new Button("one"), constraints);.add(new Button("one"), constraints);

containercontainer.add(new Button("two"), constraints);.add(new Button("two"), constraints);

Page 46: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4646

GridBagConstraints GridBagConstraints FieldsFields(Continued)(Continued) gridwidth, gridheightgridwidth, gridheight

– Specifies the number of columns and rows the Specifies the number of columns and rows the Component occupiesComponent occupies

constraints.constraints.gridwidth = 3gridwidth = 3;;– GridBagConstraints.REMAINDERGridBagConstraints.REMAINDER lets the component lets the component

take up the remainder of the row/columntake up the remainder of the row/column weightx, weightyweightx, weighty

– Specifies how much the cell will Specifies how much the cell will stretchstretch in the x or y in the x or y direction if space is left overdirection if space is left over

constraints.constraints.weightx = 3.0weightx = 3.0;;– Constraint affects the cell, not the component (use Constraint affects the cell, not the component (use fillfill))

– Use a value of 0.0 for no expansion in a directionUse a value of 0.0 for no expansion in a direction– Values are relative, not absoluteValues are relative, not absolute

Page 47: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4747

GridBagConstraints GridBagConstraints Fields (Continued)Fields (Continued) fillfill

– Specifies what to do to an element that is smaller than Specifies what to do to an element that is smaller than the cell sizethe cell size

constraints.constraints.fill = GridBagConstraints.VERTICALfill = GridBagConstraints.VERTICAL;;

– The size of row/column is determined by the The size of row/column is determined by the widest/tallest element in it widest/tallest element in it

– Can be Can be NONENONE, , HORIZONTALHORIZONTAL, , VERTICALVERTICAL, or , or BOTHBOTH anchoranchor

– If the fill is set to If the fill is set to GridBagConstraints.NONEGridBagConstraints.NONE, then the , then the anchoranchor field determines where the component is placed field determines where the component is placed

constraints.constraints.anchor = GridBagConstraints.NORTHEASTanchor = GridBagConstraints.NORTHEAST;;

– Can be Can be NORTHNORTH, , EASTEAST, , SOUTHSOUTH, , WESTWEST, , NORTHEASTNORTHEAST, , NORTHWESTNORTHWEST, , SOUTHEASTSOUTHEAST, or , or SOUTHWESTSOUTHWEST

Page 48: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4848

GridBagLayout: GridBagLayout: ExampleExample

Page 49: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4949

GridBagLayout, GridBagLayout, ExampleExample

public GridBagTest() {public GridBagTest() {

setLayout(new GridBagLayout());setLayout(new GridBagLayout());

textArea = new JTextArea(12, 40); textArea = new JTextArea(12, 40);

// 12 rows, 40 cols// 12 rows, 40 cols

bSaveAs = new JButton("Save As");bSaveAs = new JButton("Save As");

fileField = new JTextField("C:\\Document.txt");fileField = new JTextField("C:\\Document.txt");

bOk = new JButton("OK");bOk = new JButton("OK");

bExit = new JButton("Exit");bExit = new JButton("Exit");

GridBagConstraints c = new GridBagConstraints();GridBagConstraints c = new GridBagConstraints();

// Text Area.// Text Area.

c.gridx = 0;c.gridx = 0;

c.gridy = 0;c.gridy = 0;

c.gridwidth = GridBagConstraints.REMAINDER;c.gridwidth = GridBagConstraints.REMAINDER;

c.gridheight = 1;c.gridheight = 1;

c.weightx = 1.0;c.weightx = 1.0;

c.weighty = 1.0;c.weighty = 1.0;

c.fill = GridBagConstraints.BOTH;c.fill = GridBagConstraints.BOTH;

c.insets = new Insets(2,2,2,2); //t,l,b,rc.insets = new Insets(2,2,2,2); //t,l,b,r

add(textArea, c);add(textArea, c);

......

// Save As Button.// Save As Button.c.gridx = 0;c.gridx = 0;c.gridy = 1;c.gridy = 1;c.gridwidth = 1;c.gridwidth = 1;c.gridheight = 1;c.gridheight = 1;c.weightx = 0.0;c.weightx = 0.0;c.weighty = 0.0;c.weighty = 0.0;c.fill = c.fill =

GridBagConstraints.VERTICAL;GridBagConstraints.VERTICAL;add(bSaveAs,c);add(bSaveAs,c);

// Filename Input (Textfield).// Filename Input (Textfield).c.gridx = 1;c.gridx = 1;c.gridwidth = c.gridwidth =

GridBagConstraints.REMAINDER;GridBagConstraints.REMAINDER;c.gridheight = 1;c.gridheight = 1;c.weightx = 1.0;c.weightx = 1.0;c.weighty = 0.0;c.weighty = 0.0;c.fill = GridBagConstraints.BOTH;c.fill = GridBagConstraints.BOTH;add(fileField,c);add(fileField,c);......

Page 50: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5050

GridBagLayout, GridBagLayout, ExampleExample

// Exit Button.// Exit Button.c.gridx = 3;c.gridx = 3;c.gridwidth = 1;c.gridwidth = 1;c.gridheight = 1;c.gridheight = 1;c.weightx = 0.0;c.weightx = 0.0;c.weighty = 0.0;c.weighty = 0.0;c.fill = GridBagConstraints.NONE;c.fill = GridBagConstraints.NONE;add(bExit,c);add(bExit,c);

// Filler so Column 1 has nonzero width.// Filler so Column 1 has nonzero width.Component filler = Component filler = Box.createRigidArea(new Box.createRigidArea(new

Dimension(1,1));Dimension(1,1));c.gridx = 1;c.gridx = 1;c.weightx = 1.0;c.weightx = 1.0;add(filler,c);add(filler,c);......}}

With / Without Box filler at (2,1)

Page 51: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5151

Disabling the Layout Disabling the Layout ManagerManager

BehaviorBehavior– If the layout is set to If the layout is set to nullnull, then components , then components

must be must be sizedsized and and positioned positioned by handby hand

Positioning componentsPositioning components– componentcomponent..setSizesetSize(width, height)(width, height)– componentcomponent..setLocationsetLocation(left, top)(left, top)

oror– componentcomponent..setBoundssetBounds(left, top, width, height)(left, top, width, height)

Page 52: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5252

No Layout Manager, No Layout Manager, ExampleExample

setLayout(null);setLayout(null);

Button b1 = new Button("Button Button b1 = new Button("Button 1");1");

Button b2 = new Button("Button Button b2 = new Button("Button 2");2");

......

b1.setBounds(0, 0, 150, 50);b1.setBounds(0, 0, 150, 50);

b2.setBounds(150, 0, 75, 50);b2.setBounds(150, 0, 75, 50);

......

add(b1);add(b1);

add(b2);add(b2);

......

Page 53: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5353

Using Layout Using Layout Managers EffectivelyManagers Effectively

Use nested containersUse nested containers– Rather than struggling to fit your design in a single Rather than struggling to fit your design in a single

layout, try dividing the design into sectionslayout, try dividing the design into sections– Let each section be a panel with its own layout Let each section be a panel with its own layout

managermanager Turn offTurn off the layout manager for the layout manager for somesome

containerscontainers Adjust the empty space around componentsAdjust the empty space around components

– Change the space allocated by the layout managerChange the space allocated by the layout manager– Override Override insetsinsets in the in the ContainerContainer– Use a Use a CanvasCanvas or a or a BoxBox as an invisible spacer as an invisible spacer

Page 54: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5454

Nested Containers, Nested Containers, ExampleExample

Page 55: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5555

Nested Containers, Nested Containers, ExampleExamplepublic NestedLayout() {public NestedLayout() {

setLayout(new BorderLayout(2,2));setLayout(new BorderLayout(2,2));

textArea = new JTextArea(12,40); // 12 rows, 40 colstextArea = new JTextArea(12,40); // 12 rows, 40 cols

bSaveAs = new JButton("Save As");bSaveAs = new JButton("Save As");

fileField = new JTextField("C:\\Document.txt");fileField = new JTextField("C:\\Document.txt");

bOk = new JButton("OK");bOk = new JButton("OK");

bExit = new JButton("Exit");bExit = new JButton("Exit");

add(textArea,BorderLayout.CENTER);add(textArea,BorderLayout.CENTER);

// Set up buttons and textfield in bottom panel.// Set up buttons and textfield in bottom panel.

JPanel bottomPanel = new JPanel();JPanel bottomPanel = new JPanel();

bottomPanel.setLayout(new GridLayout(2,1));bottomPanel.setLayout(new GridLayout(2,1));

Page 56: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5656

Nested Containers, Nested Containers, ExampleExample JPanel subPanel1 = new JPanel();JPanel subPanel1 = new JPanel();

JPanel subPanel2 = new JPanel();JPanel subPanel2 = new JPanel(); subPanel1.setLayout(new BorderLayout());subPanel1.setLayout(new BorderLayout()); subPanel2.setLayout(new subPanel2.setLayout(new

FlowLayout(FlowLayout.RIGHT,2,2));FlowLayout(FlowLayout.RIGHT,2,2));

subPanel1.add(bSaveAs,BorderLayout.WEST);subPanel1.add(bSaveAs,BorderLayout.WEST); subPanel1.add(fileField,BorderLayout.CENTER);subPanel1.add(fileField,BorderLayout.CENTER); subPanel2.add(bOk);subPanel2.add(bOk); subPanel2.add(bExit);subPanel2.add(bExit);

bottomPanel.add(subPanel1);bottomPanel.add(subPanel1); bottomPanel.add(subPanel2);bottomPanel.add(subPanel2);

add(bottomPanel,BorderLayout.SOUTH);add(bottomPanel,BorderLayout.SOUTH); }}

Page 57: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5757

Turning Off Layout Manager Turning Off Layout Manager for Some Containers, for Some Containers, ExampleExample Suppose that you wanted to arrange a column of buttons (on Suppose that you wanted to arrange a column of buttons (on

the left) that take the left) that take exactly 40%exactly 40% of the width of the container of the width of the container setLayout(null);setLayout(null); int width1 = getSize().width*4/10;,int width1 = getSize().width*4/10;, int height = getSize().height;int height = getSize().height; Panel buttonPanel = new Panel();Panel buttonPanel = new Panel(); buttonPanel.buttonPanel.setBounds(0, 0, width1, height);setBounds(0, 0, width1, height); buttonPanel.setLayout(new GridLayout(6, 1));buttonPanel.setLayout(new GridLayout(6, 1)); buttonPanel.add(new Label("Buttons", Label.CENTER));buttonPanel.add(new Label("Buttons", Label.CENTER)); buttonPanel.add(new Button("Button One"));buttonPanel.add(new Button("Button One")); ...... buttonPanel.add(new Button("Button Five"));buttonPanel.add(new Button("Button Five")); add(buttonPanel);add(buttonPanel); Panel everythingElse = new Panel();Panel everythingElse = new Panel(); int width2 = getSize().width - width1,int width2 = getSize().width - width1, everythingElse.everythingElse.setBounds(width1+1, 0, width2, height);setBounds(width1+1, 0, width2, height);

Page 58: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5858

Turning Off Layout Turning Off Layout Manager for Some Manager for Some Containers: ResultContainers: Result

Page 59: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5959

Adjusting Space Adjusting Space Around ComponentsAround Components Change the space allocated by the layout Change the space allocated by the layout

managermanager– Most Most LayoutManagerLayoutManagers accept a horizontal s accept a horizontal

spacing (spacing (hGaphGap) and vertical spacing () and vertical spacing (vGapvGap) ) argument argument

– For For GridBagLayoutGridBagLayout, change the insets, change the insets Use a Use a CanvasCanvas or a or a BoxBox as an invisible spacer as an invisible spacer

– ForFor AWTAWT layouts, use a layouts, use a CanvasCanvas that does not that does not draw or handle mouse events as an “empty” draw or handle mouse events as an “empty” component for spacing.component for spacing.

– ForFor SwingSwing layouts, add a layouts, add a BoxBox as an invisible as an invisible spacer to improve positioning of componentsspacer to improve positioning of components

Page 60: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6060

Invisible Components Invisible Components in in Box ClassBox Class Rigid areasRigid areas

– Box.createRigidArea(Dimension dim)Box.createRigidArea(Dimension dim) Creates a two-dimensional invisible Creates a two-dimensional invisible ComponentComponent with with

a a fixed width and heightfixed width and heightComponent spacer = Component spacer = Box.createRigidArea(new Dimension(30, 40));Box.createRigidArea(new Dimension(30, 40));

StrutsStruts– Box.createHorizontalStrut(int width)Box.createHorizontalStrut(int width)– Box.createVerticalStrut(int width)Box.createVerticalStrut(int width)

Creates an invisible Creates an invisible ComponentComponent of fixed width and of fixed width and zero height, and an invisible zero height, and an invisible ComponentComponent of fixed of fixed height and zero width, respectivelyheight and zero width, respectively

Page 61: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6161

Invisible Components Invisible Components in in Box Class (Continued)Box Class (Continued) GlueGlue

– Box.createHorizontalGlue()Box.createHorizontalGlue()– Box.createVerticalGlue()Box.createVerticalGlue()

Create an invisible Create an invisible ComponentComponent that that can expand can expand horizontally or verticallyhorizontally or vertically, respectively, to fill all , respectively, to fill all remaining space remaining space

– Box.createGlue()Box.createGlue() Creates a Creates a ComponentComponent that can that can expand in both expand in both

directionsdirections A A BoxBox object achieves the glue effect by expressing object achieves the glue effect by expressing

a maximum size of a maximum size of Short.MAX_VALUEShort.MAX_VALUE Only apply Only apply glueglue to layout managers that respect to layout managers that respect

the maximum size of a the maximum size of a ComponentComponent

Page 62: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6262

Invisible Components: Invisible Components: ExampleExample

Page 63: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6363

BoxLayoutBoxLayout

BehaviorBehavior– Manager from Swing; available only in Java 2Manager from Swing; available only in Java 2– Arranges Arranges ComponentComponents either in a s either in a horizontal rowhorizontal row, , BoxLayout.X_AXISBoxLayout.X_AXIS, or in a , or in a vertical columnvertical column, , BoxLayout.Y_AXISBoxLayout.Y_AXIS

– Lays out the components in the order in which they Lays out the components in the order in which they were added to the were added to the ContainerContainer

– Resizing the container does not cause the components Resizing the container does not cause the components to relocateto relocate

– Unlike the other standard layout managers, the Unlike the other standard layout managers, the BoxLayoutBoxLayout manager cannot be shared with more than manager cannot be shared with more than one one ContainerContainer

BoxLayout layout = BoxLayout layout =

new BoxLayout(new BoxLayout(containercontainer, BoxLayout.X_AXIS);, BoxLayout.X_AXIS);

Page 64: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6464

Component Component Arrangement for Arrangement for BoxLayoutBoxLayout Attempts to arrange the components with:Attempts to arrange the components with:

– Their preferred widths (vertical layout), or Their preferred widths (vertical layout), or – Their preferred heights (horizontal layout)Their preferred heights (horizontal layout)

Vertical LayoutVertical Layout– If the components are not all the same width, If the components are not all the same width, BoxLayoutBoxLayout attempts to attempts to expand all the expand all the components to the width of the component components to the width of the component with the largest preferred widthwith the largest preferred width

– If expanding a component is not possible If expanding a component is not possible (restricted maximum size), (restricted maximum size), BoxLayoutBoxLayout aligns aligns that component horizontally in the container, that component horizontally in the container, according to the x alignment of the according to the x alignment of the componentcomponent

Page 65: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6565

Component Arrangement Component Arrangement for BoxLayout for BoxLayout (Continued)(Continued) Horizontal LayoutHorizontal Layout

– If the components are not all the same If the components are not all the same height, height, BoxLayoutBoxLayout attempts to attempts to expand expand all the components to the height of the all the components to the height of the tallest componenttallest component

– If expanding the height of a If expanding the height of a component is not possible, component is not possible, BoxLayoutBoxLayout aligns that component vertically in the aligns that component vertically in the container, according to the y container, according to the y alignment of the component.alignment of the component.

Page 66: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6666

BoxLayout: ExampleBoxLayout: Example

• All components have a 0.0 (left) alignment

• The label has a 0.0 alignment • The buttons have a 1.0 (right) alignment

Page 67: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6767

SummarySummary

Default layout managersDefault layout managers– Applet and Panel: FlowLayout Applet and Panel: FlowLayout – Frame and Dialog: BorderLayoutFrame and Dialog: BorderLayout

Layout managers respect the preferred size of Layout managers respect the preferred size of the component differentlythe component differently

GridBagLayout is the most complicated but GridBagLayout is the most complicated but most flexible managermost flexible manager– Use Use GridBagConstraintsGridBagConstraints to specify the layout of to specify the layout of

each componenteach component Complex layouts can often be simplified Complex layouts can often be simplified

through nested containersthrough nested containers In AWT use a Canvas as a In AWT use a Canvas as a spacerspacer; in Swing use ; in Swing use

a Box as a spacera Box as a spacer

Page 68: Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6868

ReferencesReferences

CWP: Chapter 11, 12CWP: Chapter 11, 12 http://java.sun.com/docs/books/tutorial/uishttp://java.sun.com/docs/books/tutorial/uis

wing/mini/layout.htmlwing/mini/layout.html http://java.sun.com/docs/books/tutorial/uishttp://java.sun.com/docs/books/tutorial/uis

wing/overview/event.htmlwing/overview/event.html http://java.sun.com/docs/books/tutorial/uishttp://java.sun.com/docs/books/tutorial/uis

wing/events/wing/events/

The End.The End. Thank you for patience!Thank you for patience!