Upload
saksham-saxena
View
244
Download
0
Embed Size (px)
Citation preview
8/10/2019 Swings Listeners and Layout
1/64
ETIT-303CSE 5thSemester
Lecture 14
8/10/2019 Swings Listeners and Layout
2/64
A layout manager allows the java programmer to develop graphicalinterfaces that will have a common appearance across theheterogeneous internet.
There are five layout managers that the programmer may choosefrom:
Flow Layout
Grid Layout
Border Layout
Card Layout
Gridbag Layout
8/10/2019 Swings Listeners and Layout
3/64
Object
Component
ButtonTextComponent
Checkbox ChoiceContainer
Label
TextArea TextField
ScrollBarCanvas
Panel ScrollPaneWindow
Part of the AWT Class Hierarchy
Dialog Frame
Applet
List
8/10/2019 Swings Listeners and Layout
4/64
Layout Managers
A Component can be displayed on a screen and a user caninteract with a Component.
A Container is a Component that can hold other Components
A Layout Manager directs the placement of Componentswithin a Container.
8/10/2019 Swings Listeners and Layout
5/64
A Containermaintains a list of Components that it manipulates as wellas a LayoutManagerto determine how components are displayed.
The Container class contains the following subclasses:
Window
Frame
Dialog
Panel
Applet
ScrollPane
8/10/2019 Swings Listeners and Layout
6/64
Containers
Method defined in class Container include:
setLayoutManager (LayoutManager)
add (Component) add Component to display
remove(Component) remove Component from display
8/10/2019 Swings Listeners and Layout
7/64
Containers
Window
A Window is a 2-dimensional drawing surface that can be displayedon an output device.
A Window can be stacked on top of other Windows and can bemoved to the front or back of the visible windows.
Methods in class Window include:
show ( ) Make the Window visible
toFront( ) Move Window to front
toBack( ) Move window to back
8/10/2019 Swings Listeners and Layout
8/64
Frame
A Frame is a type of Window with a title bar, a menu bar, a border, and acursor. It is used most frequently to display applicationsthat contain agraphical user interface or an animation.
Methods defined in Frame include:
setTitle(String) getTitle(String)
setCursor(int)
setResizable( ) make the window resizable
setMenuBar(MenuBar) include the menu bar for the window
8/10/2019 Swings Listeners and Layout
9/64
Containers
Panel
A Panel is generally used as a component in a Frame or anApplet.
It is used to group components into a single unit. The Panel with
its set of components is displayed as a single unit. It represents arectangular region of the display.
A Panelholds its own LayoutManager which may be different from theLayoutManager of the Frame or Applet in which it resides.
8/10/2019 Swings Listeners and Layout
10/64
Dialog
Always attached to an instance of Frame.
A window that is displayed for a short duration during execution.
Default LayoutManager is BorderLayoutManager (same asfor Frame)
ScrollPane
It can hold only one Component.
It does not have a LayoutManager.
If size of the component held is larger than the size of the ScrollPane,scroll bars will be automatically generated.
8/10/2019 Swings Listeners and Layout
11/64
Layout Managers
Flow Layout
Lays out components row by row from left to right.
As an example, consider an applet (subclass of Panel) that displays a
number of Buttons for selecting a language.
It is very straightforward to use, but it affords the programmer the
least ability to control the positioning of components. It is thedefault layout manager in an applet.
8/10/2019 Swings Listeners and Layout
12/64
Layout Managers
English French Greek
Japanese German
Spanish Portuguese
Arabic Chinese Russian
Applet Started
8/10/2019 Swings Listeners and Layout
13/64
Layout Managers
Constructing the previous display
importjava.awt.*;
publicclass SelectLang extends java.applet.Applet {
Button eng = newButton(English);
.
Button rus = newButton (Russian);
FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
publicvoid init ( ) {
setLayout(flow);
add(eng);
.
add(rus);
}
}
8/10/2019 Swings Listeners and Layout
14/64
Layout Managers
Suppose we wish to construct the following layout
Age 21-35 Over 65Under 20 36-65
Name
Street Address
City Zip
8/10/2019 Swings Listeners and Layout
15/64
Layout Managers
FlowLayout (intalignment, inthGap, intvGap);
In Example 1 FlowLayout(FlowLayout.LEFT, 30, 10)
A more orderly organization is achieved by first putting componentsinto panels and then placing panels in applet using Flow Layout
8/10/2019 Swings Listeners and Layout
16/64
Layout Managers
Border Layout
North
South
CenterWest East
8/10/2019 Swings Listeners and Layout
17/64
Layout Managers
Properties of a Border Layout Manager
More flexible in permitting programmer placement of components ofdifferent sizes (such as panels, canvases and text areas.
Border areas adjust to accommodate the placement of a component.The center consists of whats left over.
publicBorderLayout (inthGap, intvGap)
8/10/2019 Swings Listeners and Layout
18/64
Layout Managers
Example
A BorderLayout with a Label in North, a Scrollbar in South,a Panel containing a Checkboxgroup in West, a List in East, and aCanvas in Center.
Border Layout Example
Rectangle
Oval
Line
Fill
Background
o Redo Blueo Green
o Blacko White
8/10/2019 Swings Listeners and Layout
19/64
Layout Managers
Grid Layout
Programmer specifies the number of
rows
columns
pixels between rows, pixels between columns
GridLayout myGrid = new GridLayout (3, 2, 10, 10);
8/10/2019 Swings Listeners and Layout
20/64
Layout Managers
Grid Layout
Components expand or contract in size to fill a single gridcell. Panels, canvases, and Lists are resized to fit into a grid
cell.
Components are placed in the container in order from left to rightand top to bottom.
8/10/2019 Swings Listeners and Layout
21/64
Layout Managers
Grid Layout
name
address
8/10/2019 Swings Listeners and Layout
22/64
Layout Managers
Card Layout
A card layout is a group of components orcontainers that are displayed one at a time.
Components or containers are placed on a card using thestatement:
add (String, component);
8/10/2019 Swings Listeners and Layout
23/64
Layout Managers
Card Layout Construction
The Applet contains an ordered listing (array) of cards inone of its panels
Card Panel
8/10/2019 Swings Listeners and Layout
24/64
Layout Managers
Applet Declarations
public classCardDemo extendsApplet {privatefinal intnumCards = __; //whatever the number
privateString[ ] = newCardLabels[numCards];
//construct an array for holding CardPanel objects specified in separate file
privateCardPanel[ ] cards = newCardPanel[numCards];
privateCardLayout theLayout; //Layout for CardPanels//Create a Panel for displaying CardPanel objects in the Applet (green area)
privatePanel cardDisplayPanel;
Applet initialization
public void init ( ) {
//essential statements for card display
setLayout (newBorderLayout); //layout for the Applet
add(West, makeOtherPanel( )); //2ndparameter returns a Panel
add(Center, makeCardDisplayPanel( )); //2ndparam returns a Panel
}
8/10/2019 Swings Listeners and Layout
25/64
Layout Managers
CardPanel Objects
CardPanelsare containers with their own Components and
Layout
CardPanelis a separately declared class that extends Panel
CardPanelobjects are created in method makeCardDisplayPanel() ofApplet
CardPanelobjects are stored in the array cards
8/10/2019 Swings Listeners and Layout
26/64
Java provides two sets of facilities for developing GUIs:
The Abstract Window Toolkit (AWT): package java.awt Swing: package javax.swing
Swing architecture is rooted in the model-view-controller( MVC) design that dates back to SmallTalk .MVC architecture calls for a visual application to be brokenup into three separate parts:
A modelthat represents the data for the application.
The viewthat is the visual representation of that data.
A controllerthat takes user input on the view andtranslates that to changes in the model.
8/10/2019 Swings Listeners and Layout
27/64
Text-based interface Predetermined
sequence of events The program pauses
execution when itexpects input from theuser and continues onthe same set path after
it receives the input
Graphical interface No set sequence of
events The user can do any
number of things atany time (type in a textbox, resize thewindow, press abutton)
These responses arecalled events. We say the program is
event-driven.
8/10/2019 Swings Listeners and Layout
28/64
AWTAWT stands for Abstract windowstoolkit.
AWT components are calledHeavyweight component.
AWT components require java.awtpackage.
AWT components are platformdependent. This feature is not supported in
AWT.
SWING Swing is also called as JFCs(Java Foundation classes). Swings are called light weight component because swing
components sits on the top of AWT components and do the work. Swing components require javax.swing package. Swing components are made in purely java and they are platform
independent. We can have different look and feel in Swing.These feature is not
available in AWT.Swing has many advanced features like JTabel,Jtabbed pane which is not available in AWT. Also. Swingcomponents are called "lightweight" because they do not require anative OS object to implement their functionality. JDialog andJFrame are heavyweight, because they do have a peer. Socomponents like JButton, JTextArea, etc., are lightweight becausethey do not have an OS peer.
With Swing, you would have only one peer, the operating system'swindow object. All of the buttons, entry fields, etc. are drawn by theSwing package on the drawing surface provided by the windowobject. This is the reason that Swing has more code. It has to drawthe button or other control and implement its behavior instead ofrelying on the host operating system to perform those functions.
Swing is much larger. Swing also has very much richer functionality.
8/10/2019 Swings Listeners and Layout
29/64
INE2720 Web ApplicationSoftware Development All copyrights reserved by C.C. Cheung 2003. 29
Constructors
These three constructors apply to checkboxes that operateindependentlyof each other (i.e., not radio buttons)
Checkbox()
Creates an initially unchecked checkbox with no label
Checkbox(String checkboxLabel)
Creates a checkbox (initially unchecked) with the specified label; seesetStatefor changing it
Checkbox(String checkboxLabel, boolean state) Creates a checkbox with the specified label
The initial state is determined by the boolean value provided
A value of true means it is checked
8/10/2019 Swings Listeners and Layout
30/64
INE2720 Web ApplicationSoftware Development All copyrights reserved by C.C. Cheung 2003. 30
public class Checkboxes extends CloseableFrame {public Checkboxes() {super("Checkboxes");setFont(new Font("SansSerif", Font.BOLD,18));
setLayout(new GridLayout(0, 2));Checkbox box;for(int i=0; i
8/10/2019 Swings Listeners and Layout
31/64
INE2720 Web ApplicationSoftware Development All copyrights reserved by C.C. Cheung 2003. 31
getState/setState
Retrieves or sets the state of the checkbox: checked (true)or unchecked (false)
getLabel/setLabel Retrieves or sets the label of the checkbox
After changing the label invalidate and validate thewindow to force a new layout (same as button).
addItemListener/removeItemListener Add or remove an ItemListenerto process
ItemEvents in itemStateChanged
8/10/2019 Swings Listeners and Layout
32/64
INE2720 Web ApplicationSoftware Development All copyrights reserved by C.C. Cheung 2003. 32
CheckboxGroup Constructors
CheckboxGroup()
Creates a non-graphical object used as a tagto group checkboxes
logically together Only one checkbox associated with a particular tag can be selected
at any given time
Checkbox Constructors
Checkbox(String label, CheckboxGroup group,boolean state)
Creates a radio button associated with the specified group, with thegiven label and initial state
8/10/2019 Swings Listeners and Layout
33/64
INE2720 Web ApplicationSoftware Development All copyrights reserved by C.C. Cheung 2003. 33
import java.applet.Applet;import java.awt.*;
publicclass CheckboxGroups extends Applet {publicvoid init() {setLayout(new GridLayout(4, 2));
setBackground(Color.lightGray);setFont(new Font("Serif", Font.BOLD, 16));add(new Label("Flavor", Label.CENTER));add(new Label("Toppings", Label.CENTER));CheckboxGroup flavorGroup = new CheckboxGroup();add(new Checkbox("Vanilla", flavorGroup, true));add(new Checkbox("Colored Sprinkles"));add(new Checkbox("Chocolate", flavorGroup, false));add(new Checkbox("Cashews"));add(new Checkbox("Strawberry", flavorGroup, false));add(new Checkbox("Kiwi"));
}}
8/10/2019 Swings Listeners and Layout
34/64
INE2720 Web ApplicationSoftware Development All copyrights reserved by C.C. Cheung 2003. 34
Constructors List(int rows, boolean multiSelectable)
Creates a listbox with the specified number of visible rows
Depending on the number of item in the list (addItem or add), ascrollbar is automatically created
The second argument determines if the List is multiselectable
List() Creates a single-selectable list box with a platform-dependent
number of rows and a platform-dependent width
List(int rows) Creates a single-selectable list box with the specified number of
rows and a platform-dependent width
8/10/2019 Swings Listeners and Layout
35/64
INE2720 Web ApplicationSoftware Development All copyrights reserved by C.C. Cheung 2003. 35
import java.awt.*;
public class Lists extends CloseableFrame {public Lists() {super("Lists");setLayout(new FlowLayout());setBackground(Color.lightGray);setFont(new Font("SansSerif", Font.BOLD, 18));
List list1 = new List(3, false);list1.add("Vanilla");list1.add("Chocolate");list1.add("Strawberry");add(list1);List list2 = new List(3, true);list2.add("Colored Sprinkles");list2.add("Cashews");list2.add("Kiwi");add(list2);pack();setVisible(true);
}}
A list can be single-selectable or multi-selectable
8/10/2019 Swings Listeners and Layout
36/64
EVENT HANDING
8/10/2019 Swings Listeners and Layout
37/64
A source generates an event and sends it toone or more listeners.
The listener simply waits until it receives anevent. Listener must register with source to receive
noticification.
8/10/2019 Swings Listeners and Layout
38/64
-An event is an object that describes a statechange in a source.
-It can be generated as a consequence of a
person interacting with the elements in agraphical user interface.
Examples.Pressing a button, entering a character via thekeyboard, selecting an item in a list, andclicking the mouse, timer expires, counter,h/w or s/w failure.
8/10/2019 Swings Listeners and Layout
39/64
A source is an object that generates an event.
This occurs when the internal state of that
object changes.
A source must register listeners.
public void addTypeListener(TypeListener el)
e.g. public void addKeyListener()
8/10/2019 Swings Listeners and Layout
40/64
public void addTypeListener(TypeListener el)throwsjava.util.TooManyListenersException
public void removeTypeListener(TypeListener el)
8/10/2019 Swings Listeners and Layout
41/64
A listener is an object that is notified when anevent occurs.
It must register with one or more sources.
It must implement methods to receive andprocess these notifications.
8/10/2019 Swings Listeners and Layout
42/64
8/10/2019 Swings Listeners and Layout
43/64
EventObject(java.util)
AWTEvent(java.awt)
8/10/2019 Swings Listeners and Layout
44/64
EventObject contains two methods:getSource( ) and toString()
The getSource( ) method returns the source
of the event.
general form : Object getSource( )
-The class AWTEvent, defined within thejava.awt package which is a sub class ofEventObject.
-AWTEvent is a su erclass of all AWT events
8/10/2019 Swings Listeners and Layout
45/64
8/10/2019 Swings Listeners and Layout
46/64
8/10/2019 Swings Listeners and Layout
47/64
8/10/2019 Swings Listeners and Layout
48/64
Listeners are created by implementing one ormore of the interfaces defined by the
java.awt.event package.
When an event occurs, the event source invokes
the appropriate method defined by the listenerand provides an event object as its argument.
8/10/2019 Swings Listeners and Layout
49/64
8/10/2019 Swings Listeners and Layout
50/64
8/10/2019 Swings Listeners and Layout
51/64
void actionPerformed(ActionEvent ae)
8/10/2019 Swings Listeners and Layout
52/64
Void adjustmentValueChanged(AdjustmentEvent ae)
8/10/2019 Swings Listeners and Layout
53/64
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
8/10/2019 Swings Listeners and Layout
54/64
void componentAdded(ContainerEvent ce)Void componrntListener(ContainerEvrnt ce)
void componentRemoved(ContainerEvent ce)
8/10/2019 Swings Listeners and Layout
55/64
void focusLost(FocusEventfe)
void focusGained(FocusEventfe)
8/10/2019 Swings Listeners and Layout
56/64
void itemStateChanged(ItemEvent ie)
8/10/2019 Swings Listeners and Layout
57/64
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
8/10/2019 Swings Listeners and Layout
58/64
void mouseClicked(MouseEvent me)void mouseEntered(MouseEvent me)void mouseExited(MouseEvent me)void mousePressed(MouseEvent me)void mouseReleased(MouseEvent me)
8/10/2019 Swings Listeners and Layout
59/64
void mouseDragged(MouseEvent me)void mouseMoved(MouseEvent me)
8/10/2019 Swings Listeners and Layout
60/64
8/10/2019 Swings Listeners and Layout
61/64
void textChanged(TextEvent te)
8/10/2019 Swings Listeners and Layout
62/64
void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)
8/10/2019 Swings Listeners and Layout
63/64
void windowActivated(WindowEvent we)void windowClosed(WindowEvent we)void windowClosing(WindowEvent we)
void windowDeactivated(WindowEventwe
)void windowDeiconified(WindowEvent we)void windowIconified(WindowEvent we)void windowOpened(WindowEvent we)
8/10/2019 Swings Listeners and Layout
64/64
void menuCanceled(MenuEvente) void menuDeselected(MenuEvente) void menuSelected(MenuEvente)
http://docs.oracle.com/javase/7/docs/api/javax/swing/event/MenuListener.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/event/MenuListener.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/event/MenuListener.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/event/MenuEvent.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/event/MenuEvent.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/event/MenuListener.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/event/MenuEvent.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/event/MenuEvent.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/event/MenuEvent.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/event/MenuEvent.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/event/MenuListener.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/event/MenuEvent.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/event/MenuListener.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/event/MenuEvent.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/event/MenuListener.html