13 2 Event Handling and Layout Managers

Embed Size (px)

Citation preview

  • 8/14/2019 13 2 Event Handling and Layout Managers

    1/60

    1Java

    Event Handling and Layout

    Managers

  • 8/14/2019 13 2 Event Handling and Layout Managers

    2/60

  • 8/14/2019 13 2 Event Handling and Layout Managers

    3/60

    3Java

    Null Layout Manager23

    Constructors and Methods22

    GridLayout21

    Constructors and Methods20

    BorderLayout19

    Constructors and Methods18

    FlowLayout17

    Layout Manager Classes16MouseListener and MouseEvent15

    ItemListener and ItemEvent14

    WindowAdapter13

    Adapters12

    Contents

  • 8/14/2019 13 2 Event Handling and Layout Managers

    4/60

    4Java

    Know

    How the Delegation event model works

    Listeners and Adapter classes

    Layout Managers

  • 8/14/2019 13 2 Event Handling and Layout Managers

    5/60

    5Java

    Be able to

    Implement Listeners and Adapter classes

    Use Layout Managers effectively

  • 8/14/2019 13 2 Event Handling and Layout Managers

    6/60

    6Java

    Club where sports event happen

    Inter ClubSports

    Event

    I must register

    myself as a club

    member so that

    when an event

    happens, the club

    informs me.

    Annual Sports

    EventI run

    I run

    Anu

    Raj

  • 8/14/2019 13 2 Event Handling and Layout Managers

    7/60

    7Java

    Sports club where sports event happen

    Inter ClubSports

    Event

    Annual Sports

    EventI run

    I run

    Annual eventhappening .

    Please run.

    Anu

    Raj

  • 8/14/2019 13 2 Event Handling and Layout Managers

    8/60

    8Java

    Source object

    Inter ClubSports

    Event

    Annual Sports

    Event

    Listeners objects

    Event object

    Java terminology

    Anu

    Raj

  • 8/14/2019 13 2 Event Handling and Layout Managers

    9/60

    9Java

    Source has list of athletes objects

    (Anu, Raj). Source will ensure that

    they have run() method. When event

    happens source will call anu.run()and raj.run()

    Annual Sports

    Event

    Register me. I

    have

    implemented

    Running

    Java way of handling events

    Anu

    Raj

    Inviting members whocan run.(Only objectswhich implements

    Running (run()method))

  • 8/14/2019 13 2 Event Handling and Layout Managers

    10/60

    10Java

    The Delegation Event Model

    Source(Ex. JButton)

    Listener (Ex. JFrame)

    2. Generates events(user clicks)

    Event

    object

    3. Calls a method on the

    Listener and sends event object

    1. Registers itself to receive events

  • 8/14/2019 13 2 Event Handling and Layout Managers

    11/60

    11Java

    Event types

    Low level events

    Examples:

    Pressing keyboard buttons

    Mouse clicks

    Semantic events:

    Examples:

    Button click

    Selecting an item in the list

  • 8/14/2019 13 2 Event Handling and Layout Managers

    12/60

    12Java

    Low level events

    MouseEvent

    KeyEvent

    Generated by all the components.

  • 8/14/2019 13 2 Event Handling and Layout Managers

    13/60

    13Java

    JButton, JMenuItem, JRadioButton,JCheckbox, JTextField:

    java.awt.event.ActionEvent JTextField ,JTextArea, JPasswordField:

    java.awt.event.InputMethodEvent

    JTabbedPanejavax.swing.event.ChangeEvent

    JFrame:

    java.awt.event.WindowEvent JCombo:

    java.awt.event.ItemEvent JList:

    javax.swing.event.ListSelectionEvent

    Semantic events

  • 8/14/2019 13 2 Event Handling and Layout Managers

    14/60

    14Java

    EventObject

    Root class for all event objects

    Object getSource()

    A method in EventObject class.

    Which returns us the source object on which the

    Event initially occurred.

  • 8/14/2019 13 2 Event Handling and Layout Managers

    15/60

    15Java

    Listeners XxxListener is an interface any source would

    implement if it is interested in a particularXxxevent.

    A source generating an XxxEvent would allowonly those components to register with it whohave implemented XxxListener.

    XxxListener will have one or more methodswhich sources interested in the vent wouldimplement.

    When event occurs the source will call themethod of XxxListener for all the componentswho have registered with it.

  • 8/14/2019 13 2 Event Handling and Layout Managers

    16/60

    16Java

    Listeners Interfaces

    corresponding to each Event

    object

    ActionEvent ActionListener

    InputMethodEvent InputMethodListener ChangeEvent ChangeListener

    WindowEvent WindowListener

    ItemEvent ItemListener ListSelectionEvent ListSelectionListener

    java.awt.event

    javax.swing.event

  • 8/14/2019 13 2 Event Handling and Layout Managers

    17/60

    17Java

    Registering the listener with

    the source

    source.addXxxListener(XxxListener t)

    where

    source is any Component

    Xxx: could be any one of the Listenermentioned in the previous slide

  • 8/14/2019 13 2 Event Handling and Layout Managers

    18/60

    18Java

    What are we going to look at?

    We will look at only the below

    listed Events. The others are very

    similar. You can get all the

    information about Listenermethods and Event methods from

    the API.

    1.ActionListener2.WindowListener

    3.ItemListener

    4.MouseListener

  • 8/14/2019 13 2 Event Handling and Layout Managers

    19/60

    19Java

    ActionListener andActionEvent

    Source that generates ActionEvent:

    Button object is clicked

    MenuItem object is selected

    List object is double clicked

    Listener: ActionListener

    public void actionPerformed(ActionEvent e)

    Useful ActionEvent method: public String getActionCommand()

  • 8/14/2019 13 2 Event Handling and Layout Managers

    20/60

    20Java

    Example

    On clicking2. Red - the panelbecomes Red.

    3. Green - the panelbecomes Green

    4. Blue - the panelbecomes Blue.

  • 8/14/2019 13 2 Event Handling and Layout Managers

    21/60

    21Java

    import javax.swing.*;

    import java.awt.event.*;

    import java.awt.Color;public class ColorFrame extends JFrameimplements ActionListener{

    JPanel panel =new JPanel();

    public ColorFrame (){

    super("Simple Frame With Color Button");

    setSize(300,300);

    setVisible(true);

    JButton red=new JButton("Red");

    JButton green=new JButton("Green");

    JButton blue=new JButton("Blue");

    Creating buttonsExample 1

  • 8/14/2019 13 2 Event Handling and Layout Managers

    22/60

    22Java

    panel.add(red);

    panel.add(blue);

    panel.add(green);getContentPane().add(panel);

    red.addActionListener(this);

    green.addActionListener(this);

    blue.addActionListener(this);

    }public void actionPerformed(

    ActionEvent e){

    if(e.getActionCommand().equals("Red"))

    panel.setBackground(Color.red);

    Adding buttons to thepanel and panel to theframe.

    Register the current object with the buttons

  • 8/14/2019 13 2 Event Handling and Layout Managers

    23/60

    23Java

    if(e.getActionCommand().equals("Green"))

    panel.setBackground(Color.green);

    if(e.getActionCommand().equals("Blue"))

    panel.setBackground(Color.blue);

    }public static void main(String str[]){

    new ColorFrame();

    }}

  • 8/14/2019 13 2 Event Handling and Layout Managers

    24/60

    24Java

    If you dont mind can we handle the frame

    close event. I am tried of pressing control-C.

    Sure!

  • 8/14/2019 13 2 Event Handling and Layout Managers

    25/60

    25Java

    WindowListener and WindowEvent Source And Event: Frame close,open, minimize,

    maximize

    Listener: WindowListener

    void windowClosing(WindowEvent e)

    void windowClosed(WindowEvent e)

    void windowOpened(WindowEvent e)

    void windowDeiconified(WindowEvent e)

    void windowIconified(WindowEvent e)

    void windowActivated(WindowEvent e)

    void windowDeactivated(WindowEvent e)

  • 8/14/2019 13 2 Event Handling and Layout Managers

    26/60

    26Java

    You mean I will have to implement 7 methods

    to handle window closing event ! I think I amok with control-C.

    Surely not. Java creators

    knew about the

    programmers reaction tothis. They created Adapter

    classes for rescue.

  • 8/14/2019 13 2 Event Handling and Layout Managers

    27/60

    27Java

    Adapters

    Adapter classes are useful when we want to

    override only methods we are interested in.

    Adapter classes implement the the listener

    interfaces and provide empty implementation

    for all the methods defined in the interface.

  • 8/14/2019 13 2 Event Handling and Layout Managers

    28/60

  • 8/14/2019 13 2 Event Handling and Layout Managers

    29/60

    29Java

    I dont understand how Adapterswill help. My frame class already

    extends Frame. So my frame classcannot inherit from Adapter noMULTIPLE INHERITANCE in Java.

    If we implement using WindowListener, thesource and the listener both are the sameobject. With Adapters, we delegate the eventhandling to WindowAdapter object.So wedont have to inherit from Adapter class.

  • 8/14/2019 13 2 Event Handling and Layout Managers

    30/60

    30Java

    //import statements

    public class ColorFrame extends Frameimplements ActionListener{

    WindowAdapter win;

    public ColorFrame(){

    super("Simple Frame With Menu");

    win= new WindowAdapter(){Example 2

  • 8/14/2019 13 2 Event Handling and Layout Managers

    31/60

  • 8/14/2019 13 2 Event Handling and Layout Managers

    32/60

    32Java

    Oh it has become so incredibly easyand the code also looks very

    professional. I use to hate inner classbut I think now I have started liking it.

    Having said all this about adaptersjust remember that we haveAdapter classes only for those

    Listener interfaces which havemore than one method. (It makesperfect sense, right!)

  • 8/14/2019 13 2 Event Handling and Layout Managers

    33/60

    33Java

    ItemListener and ItemEvent

    Source And Event: Checkbox or a List item is

    clicked or a Choice is selected or deselected.

    Listener: ItemListener

    public voiditemStateChanged(ItemEvent e)

    Interesting ItemEvent method

    int getStateChange()ItemEvent.SELECTED

    ItemEvent.DESELECTED

  • 8/14/2019 13 2 Event Handling and Layout Managers

    34/60

    34Java

    import java.awt.*;

    import java.awt.event.*;

    import javax.swing.*;public class ColorAWT extends JFrame

    implementsItemListener{

    JComboBox colors;

    JPanel panel= new JPanel();

    ColorAWT() {

    super("Item listener");

    colors=new JComboBox();

    colors.addItem("Red");

    colors.addItem("Green");

    Adding items intothe combo box

    Example 3

  • 8/14/2019 13 2 Event Handling and Layout Managers

    35/60

    35Java

    colors.addItem("Blue");

    panel.add(colors);

    getContentPane().add(panel);setSize(200,200);

    setVisible(true);

    colors.addItemListener(this);}

    public void itemStateChanged(ItemEvent ie

    {

    String

    color=(String)colors.getSelectedItem();

    if(color.equals("Red"))

    panel.setBackground(Color.RED);

  • 8/14/2019 13 2 Event Handling and Layout Managers

    36/60

  • 8/14/2019 13 2 Event Handling and Layout Managers

    37/60

    37Java

    MouseListener and MouseEvent

    Source and event: Mouse button pressed,released etc.

    Listener: MouseListener

    void mouseClicked(MouseEvent e)

    void mouseEntered(MouseEvent e)

    void mouseExited(MouseEvent e)

    void mousePressed(MouseEvent e)

    void mouseReleased(MouseEvent e)

    MouseEvent methods:

    public int getX() ,public int getY()

  • 8/14/2019 13 2 Event Handling and Layout Managers

    38/60

    38Java

    Exactly!

    Lets us draw lines on theframe. Each click of the

    mouse will determine the

    start point and the end point

    of the line.

    We certainly can use MouseAdapter

    instead of typing this long list of methods

    of MouseListerner, right!

  • 8/14/2019 13 2 Event Handling and Layout Managers

    39/60

    39Java

    import java.awt.*;

    import java.awt.event.*;

    Import javax.swing.*;

    public class DrawLines extends JFrame {

    int x1=0;

    int y1=0;

    int x2,y2;

    boolean firstPoint=true;

    DrawLines() {

    super("Mouse Listener");setSize(600,600);

    setVisible(true);

    setBackground(Color.white);

    Example 4

  • 8/14/2019 13 2 Event Handling and Layout Managers

    40/60

    40Java

    MouseAdapter ma= new MouseAdapter(){

    public void mousePressed(MouseEvent me)

    {

    if(firstPoint)

    { x1=me.getX();y1=me.getY()

    ;

    firstPoint=false; }

    x2=me.getX();

    y2=me.getY();

    draw(); }};

    this.addMouseListener(ma);

  • 8/14/2019 13 2 Event Handling and Layout Managers

    41/60

  • 8/14/2019 13 2 Event Handling and Layout Managers

    42/60

  • 8/14/2019 13 2 Event Handling and Layout Managers

    43/60

    43Java

    FlowLayout

    A flow layout arranges components one afteranother from left to right, top to bottom. The flowdirection can also be changed to right to left.

    The alignment can be either left, right centered.

    By default it is centered. All the examples for the applet that we have seen

    so far arranges the components in the flowlayout.

  • 8/14/2019 13 2 Event Handling and Layout Managers

    44/60

    44Java

    Constructors and Methods

    FlowLayout()

    FlowLayout(int align)

    FlowLayout(int align,int hgap,int vgap)

    Getters and setter for

    alignment

    hgap

    vgap

    FlowLayout.CENTERFlowLayout.LEFT

    FlowLayout.RIGHT

    Horizontal gap and Vertical gap

  • 8/14/2019 13 2 Event Handling and Layout Managers

    45/60

    45Java

    BorderLayout

    The border layout divides the containers area intonorth, south, east, west and center.

  • 8/14/2019 13 2 Event Handling and Layout Managers

    46/60

    46Java

    Constructors and Methods

    BorderLayout()

    BorderLayout(int hgap, int vgap)

    Setters and getters for

    hgap and vgap

  • 8/14/2019 13 2 Event Handling and Layout Managers

    47/60

    47Java

    import javax.swing.*;

    import java.awt.*;

    import java.awt.event.*;public class BorderExample extends JFrame

    implements ActionListener{

    JPanel colorPanel= new JPanel();

    public static void main(String s[]){new BorderExample ();}

    BorderExample() {

    JPanel buttonPanel= new JPanel();

    colorPanel.setBackground(Color.white);

    Example 5

  • 8/14/2019 13 2 Event Handling and Layout Managers

    48/60

    48Java

    setVisible(true);

    setSize(300,100);

    JButton red = new JButton("Red", new

    ImageIcon("red.GIF"));

    JButton green = new JButton("Green",new

    ImageIcon("green.GIF"));JButton blue = new JButton("Blue",new

    ImageIcon("blue.GIF"));

    buttonPanel.add(red);

    buttonPanel.add(green);buttonPanel.add(blue);

  • 8/14/2019 13 2 Event Handling and Layout Managers

    49/60

    49Java

    getContentPane().add(buttonPanel,BorderLayout.NORTH);

    getContentPane().add(colorPanel,

    BorderLayout.CENTER);

    red.addActionListener(this);

    green.addActionListener(this);

    blue.addActionListener(this);validate();

    }

  • 8/14/2019 13 2 Event Handling and Layout Managers

    50/60

    G idL t

  • 8/14/2019 13 2 Event Handling and Layout Managers

    51/60

    51Java

    GridLayout

    This layout manager lays out a container'scomponents in a rectangular grid specified by

    rows and columns in the constructor.

    The entire area of the container is divided into

    grid of equal sizes.

    We change our Login

    form that we createdin swing chapter toproper format.

  • 8/14/2019 13 2 Event Handling and Layout Managers

    52/60

    52Java

    Constructors and Methods

    GridLayout()

    GridLayout(int rows, int cols)

    GridLayout(int rows, int cols,int hgap,

    int vgap)Setters and getters for

    hgap,vgap, rows and columns

  • 8/14/2019 13 2 Event Handling and Layout Managers

    53/60

    53Java

    3 rows and 2 columns:GridLayout(3,2))

  • 8/14/2019 13 2 Event Handling and Layout Managers

    54/60

    54Java

    import javax.swing.*;

    import java.awt.*;

    public class TestJFC extends JFrame {

    public static void main(String s[]) {

    new TestJFC();}

    TestJFC() {

    setVisible(true);setSize(300,120);

    JPanel p= new JPanel();

    p.setBackground(Color.white);

    p.setLayout(new GridLayout(3,2));p.setBorder(BorderFactory.createMatteBo

    rder(-1,-1,-1,-1,newImageIcon("bullet.gif")));

    p.add(new JLabel("Login"));

    Example 6

  • 8/14/2019 13 2 Event Handling and Layout Managers

    55/60

    55Java

    JTextField login= new JTextField(10);

    p.add(login);

    p.add(new JLabel("Password"));

    JPasswordField pass= newJPasswordField(10);

    p.add(pass);

    Stringroles[]={"Student","Teacher","HOD","Management"};

    p.add(new JLabel("Role"));

    JComboBox role= new JComboBox(roles);

    p.add(role);

    getContentPane().add(p);

    validate();}}

  • 8/14/2019 13 2 Event Handling and Layout Managers

    56/60

    56Java

    There are many more layout

    managers. But if you are not

    happy with any, then you canlayout the components as you

    wish by setting the layout

    manager to null.

    What if I want to layout components and I

    have no layout managers that will layout

    in the way I want.

  • 8/14/2019 13 2 Event Handling and Layout Managers

    57/60

  • 8/14/2019 13 2 Event Handling and Layout Managers

    58/60

    58Java

    import javax.swing.*;

    public class BoundsDemo extends JFrame{

    public BoundsDemo(){

    super("Boundslayout");

    setSize(350,200);

    setVisible(true);

    getContentPane().setLayout(null);JLabel lLogin=new JLabel("Login:");

    JTextField login = new JTextField(20);

    JLabel lPassword=new

    JLabel("Password:");JPasswordField password = new

    JPasswordField(20);

    JButton b= new JButton("Submit");

    Example 7

  • 8/14/2019 13 2 Event Handling and Layout Managers

    59/60

    59Java

    lLogin.setBounds(30,30,100,15);

    login.setBounds(150,30,100,20);

    lPassword.setBounds(30,80,100,20);password.setBounds(150,80,100,20);

    b.setBounds(150,150,100,20);

    getContentPane().add(lLogin);

    getContentPane().add(login);

    getContentPane().add(lPassword);

    getContentPane().add(password);

    getContentPane().add(b);

    repaint();

    }

  • 8/14/2019 13 2 Event Handling and Layout Managers

    60/60

    60

    public static void main(String str[]){

    new BoundsDemo();}

    }