0% found this document useful (0 votes)
2 views

Components and Event Handling

The document provides an overview of various layout managers in Java, including FlowLayout, BorderLayout, GridLayout, GridBagLayout, and CardLayout, each with its constructors and examples. It also discusses Java controls for GUI design, such as labels, buttons, checkboxes, and text fields, along with the ActionEvent and MouseEvent classes for handling user interactions. The document outlines the structure and functionality of these components to aid in creating effective graphical user interfaces.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Components and Event Handling

The document provides an overview of various layout managers in Java, including FlowLayout, BorderLayout, GridLayout, GridBagLayout, and CardLayout, each with its constructors and examples. It also discusses Java controls for GUI design, such as labels, buttons, checkboxes, and text fields, along with the ActionEvent and MouseEvent classes for handling user interactions. The document outlines the structure and functionality of these components to aid in creating effective graphical user interfaces.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

COMPONENTS

AND EVENT
HANDLING AND
LAYOUT
TYPES OF LAYOUTS
1. FlowLayout :-
The flow layout, is the most basic layout manager in which
components are placed from left to right, as they were added. When the
horizontal row is too small, to put all the components in one row, then it uses
multiple rows. You can align the components left, right, or center (default).
 Constructors of FlowLayout class :-
 FlowLayout(): creates a flow layout with centered alignment and a default
5 unit horizontal and vertical gap.

 FlowLayout(int align): creates a flow layout with the given alignment and
a default 5 unit horizontal and vertical gap.

 FlowLayout(int align, int hgap, int vgap): creates a flow layout with the
given alignment and the given horizontal and vertical gap.
 Example:- public class DEMO
{ public static void main(String[] args)
import java.awt.*; {
class MyFlowLayout new MyFlowLayout();
{ Frame f; }
MyFlowLayout() }
{ f=new Frame();
Button b1=new Button("1");  Output:-
Button b2=new Button("2");
Button b3=new Button("3");
Button b4=new Button("4");
Button b5=new Button("5");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);

f.setLayout(new
FlowLayout(FlowLayout.RIGHT));
f.setSize(300,300);
f.setVisible(true);
}
}
2. BorderLayout :-
In the Border Layout Manager, the components are positioned in
five different areas. In other words, North, South, East, West and Center.
Each area may contain only one component. If you enlarge the window, you
will notice that the center area gets as much of the newly available space, as
possible. The other area will expand, only as much as necessary, to keep the
available space filled.
 Constructors of BorderLayout class :-
 BorderLayout(): creates a border layout but with no gaps between the
components.
 BorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.
 Example :- public class DEMO
{ public static void main(String[] args)
import java.awt.*; {
class BorLayout new BorLayout();
{ BorLayout() }
{ Frame f=new Frame(); }
f.setLayout(new BorderLayout());
Button b1 = new Button("NORTH");  Output :-
Button b2 = new Button("SOUTH");
Button b3 = new Button("EAST");
Button b4 = new Button("WEST");
Button b5 = new Button("CENTER");
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
}
3. GridLayout :-
Grid Layout is used to place the components in a grid of cells
(rectangular). The layout manager divides the container into a grid, so that
components can be placed in rows and columns. Each component will have
the same width and height. The components are added to the grid starting at
the top-left cell and proceeding left-to-right, until the row is full. Then go to
the next row.
 Constructors of GridLayout class :-
 GridLayout(): creates a grid layout with one column per component in a
row.
 GridLayout(int rows, int columns): creates a grid layout with the given
rows and columns but no gaps between the components.
 GridLayout(int rows, int columns, int hgap, int vgap): creates a grid
layout with the given rows and columns alongwith given horizontal and
vertical gaps.
 Example :- f.setLayout(new GridLayout());
f.setSize(300,300);
import java.awt.*; f.setVisible(true);
class MyGridLayout }
{ MyGridLayout() }
{ Frame f=new Frame(); public class DEMO2
Button b1 = new Button("1"); { public static void main(String[] args)
Button b2 = new Button("2"); {
Button b3 = new Button("3"); new MyGridLayout();
Button b4 = new Button("4"); }
Button b5 = new Button("5"); }
Button b6 = new Button("6");
Button b7 = new Button("7");  Output :-
Button b8 = new Button("8");

f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(b7);
f.add(b8);
4. GridBagLayout :-
GridBagLayout is one of the most flexible — and complex —
layout managers the Java platform provides. A GridBagLayout places
components in a grid of rows and columns, allowing specified components to
span multiple rows or columns. Not all rows necessarily have the same
height. Similarly, not all columns necessarily have the same width.
Essentially, GridBagLayout places components in rectangles (cells) in a grid,
and then uses the components' preferred sizes to determine how big the cells
should be.
 Example :- gcon.gridx = 0;
import java.awt.*; gcon.gridy = 0;
gcon.gridheight=1;
class MyGridBagLayout extends Frame gcon.gridwidth = 2;
{ gb.setConstraints(b1, gcon);
public MyGridBagLayout() add(b1);
{
Button b1 = new Button("Btn 1"); gcon.gridx = 2;
Button b2 = new Button("Btn 2"); gb.setConstraints(b2, gcon);
Button b3 = new Button("Btn 3"); add(b2);
Button b4 = new Button("Btn 4");
Button b5 = new Button("Btn 5"); gcon.gridx = 0;
Button b6 = new Button("Btn 6"); gcon.gridy = 1;
Button b7 = new Button("Btn 7"); gcon.gridwidth = 1;
Button b8 = new Button("Btn 8"); gb.setConstraints(b3, gcon);
Button b9 = new Button("Btn 9"); add(b3);

GridBagLayout gb = new GridBagLayout(); gcon.gridx = 1;


setLayout(gb); gb.setConstraints(b4, gcon);
GridBagConstraints gcon = new add(b4);
GridBagConstraints();
gcon.weightx = 1; gcon.gridx = 2;
gcon.weighty = 1; gb.setConstraints(b5, gcon);
gcon.fill = GridBagConstraints.BOTH; add(b5);
gcon.gridx = 3; setSize(300, 300);
gb.setConstraints(b6, gcon); setVisible(true);
add(b6); }
}
gcon.gridx = 0; public class DEMO2
gcon.gridy = 2; {
gcon.gridwidth = 3; public static void main(String[] args)
gb.setConstraints(b7, gcon); {
add(b7); MyGridBagLayout a = new
MyGridBagLayout();

gcon.gridx = 0; }

gcon.gridy = 3; }
 Output :-
gcon.gridwidth = 3;
gb.setConstraints(b8, gcon);
add(b8);

gcon.gridx = 3;
gcon.gridy = 2;
gcon.gridheight=2;
gcon.gridwidth = 1;
gb.setConstraints(b9, gcon);
add(b9);
5. CardLayout :-
The CardLayout class manages the components in such a manner that
only one component is visible at a time. It treats each component as a card that is
why it is known as CardLayout.

 Constructors of CardLayout class:-


 CardLayout(): creates a card layout with zero horizontal and vertical gap.
 CardLayout(int hgap, int vgap): creates a card layout with the given
horizontal and vertical gap.

 Commonly used methods of CardLayout class :-


1. public void next(Container parent): is used to flip to the next card of the
given container.
2. public void previous(Container parent): is used to flip to the previous
card of the given container.
3. public void first(Container parent): is used to flip to the first card of the
given container.
4. public void last(Container parent): is used to flip to the last card of the
given container.
5. public void show(Container parent, String name): is used to flip to the
specified card with the given name.
 Example :- b1.addActionListener(this);
b2.addActionListener(this);
import java.awt.*; b3.addActionListener(this);
import java.awt.event.*;
import javax.swing.JFrame; c.add(b1);
import javax.swing.*; c.add(b2);
c.add(b3);
public class MyCardLayout extends JFrame }
implements ActionListener public void actionPerformed(ActionEvent e)
{ {
CardLayout card; card.next(c);
JButton b1, b2, b3; }
Container c; public static void main(String[] args)
MyCardLayout() {
{ Demo3 cl = new Demo3();
c = getContentPane(); cl.setSize(400, 400);
card = new CardLayout(40, 30); cl.setVisible(true);
c.setLayout(card); }
}
b1 = new JButton("GEEKS");
b2 = new JButton("FOR");
b3 = new JButton("HELLO");
 Output :-
CONTROL FUNDAMENTALS
 Java controls are the controls that are used to design graphical user
interfaces or web applications.
 To make an effective GUI, Java provides java.awt package that
supports various AWT controls like Label, Button, CheckBox,
CheckBox Group, List, Text Field, Text Area, Choice, Scrollbar,
Dialog, File Dialog, etc that creates or draw various components on
web and manage the GUI based application.
 The following are the list of commonly used GUI elements
commonly known as Graphical User Interface.

1. Label :- A label is a user for placing text inside the container. A label
is used only for inputting text. The label does not imply that the text
can be altered or it can be used as a button which can be further
worked upon.
Label n=new Label("Name:",Label.CENTER);
2. Button :- This command generates a button in the User Interface.
Clicking on the button would move the command to another page or
another web server which is used to show several other outputs in
the user interface page.
Button b1=new Button("submit");

3. Checkbox :- There can be a certain question and the checkbox is


used to determine the true or false nature of the question being
asked. If the checkbox is ticked then it means that the said question
is true which if it is unchecked it means that the said question is
false.
Checkbox checkbox1 = new Checkbox("Hello World");

4. Checkbox Group :- As the name implies the checkbox group is a


set of checkboxes that are being used in the programming language.
There are many checkboxes that are being used and hence the group
of checkboxes is known as the checkbox group.
CheckboxGroup cb = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("Hello", cb, true);
5. List :- The list gives a scrolling list of items for the user. The
scrolling list of items is also being set by the user. The user sets the
scrolling list of items such as Fruits, Vegetables, some questionnaire
or other facts.
List l1=new List(4);

6. Text Field :- A text field is used for the editing of a particular line of
text which can be used within the programming concept.
TextField t1 = new TextField(20);

7. Text Area:- A text area is used for the editing of multiple lines of
text. The only difference between the Text field and Text area is that
Text Field is used for editing a single line of text within the user
interface while a Text Area is used for editing multiple lines of text.

TextArea area=new TextArea("Welcome to the universe");


area.setBounds(10,30, 300,300);
8. Choice :- A choice, as the name implies, shows the various options
and the choice that is selected is shown in the top menu bar of the
screen.
Choice c=new Choice();
c.setBounds(100,100, 75,75);
c.add("Subject 1");
c.add("Subject 2");
c.add("Subject 3");
c.add("Subject 4");
c.add("Subject 5");
ACTIONEVENT CLASS
 The Java ActionListener is notified whenever you click on the button or menu
item. It is notified against ActionEvent.
 The ActionListener interface is found in java.awt.event package.
 It has only one method: actionPerformed() method.
 The actionPerformed() method is invoked automatically whenever you click on
the registered component.
public abstract void actionPerformed(ActionEvent e);
 The common approach to implement the ActionListener. If you implement the
ActionListener class, you need to follow 3 steps :-
1. Implement the ActionListener interface in the class :-
public class MyActionEvent Implements ActionListener
2. Register the component with the Listener :-
component.addActionListener(instanceOfListenerclass);
3. Override the actionPerformed() method :-
public void actionPerformed(ActionEvent e)
{ //Write the code here }
 Example:- public void actionPerformed(ActionEvent e)
import java.awt.*; {
import java.awt.event.*; t.setText("Welcome to Javatpoint.");
}
class MyActionEvent implements ActionListener }
{ public class Demo
TextField t; {
MyActionEvent() public static void main(String[] args)
{ {
Frame f = new Frame(); MyActionEvent a = new MyActionEvent ();
t = new TextField(); }
t.setBounds(50,50, 150,20); }
Button b = new Button("Click Here");  Output :-
b.setBounds(50,100,60,30);
b.addActionListener(this);
f.add(b);
f.add(t);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
MOUSEEVENT CLASS
 The Java MouseListener is notified whenever you change the state of
mouse. It is notified against MouseEvent.
 The MouseListener interface is found in java.awt.event package.
 It has five methods:-
1. public abstract void mouseClicked(MouseEvent e);
2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);
 Example :- public void mouseEntered(MouseEvent e)
{
import java.awt.*; l.setText("Mouse Entered");
import java.awt.event.*; }
public void mouseExited(MouseEvent e)
class Abc extends Frame implements MouseListener {
{ l.setText("Mouse Exited");
Label l; }
Abc() public void mousePressed(MouseEvent e)
{ {
addMouseListener(this); l.setText("Mouse Pressed");
l = new Label(); }
l.setBounds(20,50,100,20); public void mouseReleased(MouseEvent e)
add(l); {
setSize(500,300); l.setText("Mouse Released");
setLayout(null); }
setVisible(true); }
} public class Demo
public void mouseClicked(MouseEvent e) {
{ public static void main(String[] args)
l.setText("Mouse Clicked"); {
} Abc a = new Abc();
}
}
 Output :-
 The Java MouseMotionListener is notified whenever you move or
drag mouse.
 It is notified against MouseEvent.
 The MouseMotionListener interface is found in java.awt.event
package.

 It has two methods :-


1. public abstract void mouseDragged(MouseEvent e) : Invoked
when a mouse button is pressed on a component and then dragged.
2. public abstract void mouseMoved(MouseEvent e) : Invoked when
the mouse cursor has been moved onto a component but no buttons
have been pushed.
 Example :- public void mouseMoved(MouseEvent e)
{
import java.awt.*; Graphics g=getGraphics();
import java.awt.event.*; g.setColor(Color.RED);
g.fillOval(e.getX(),e.getY(),20,20);
class MyMouse extends Frame implements }
MouseMotionListener }
{ public class MyMouseEvent
MyMouse() {
{ public static void main(String[] args)
addMouseMotionListener(this); {
setSize(300,300); MyMouse a = new MyMouse();
setLayout(null); }
setVisible(true); }
}
public void mouseDragged(MouseEvent e)  Output :-
{
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);
}
KEYEVENT CLASS
 Key events indicate when the user is typing at the keyboard.
 Specifically, key events are fired by the component with the keyboard
focus when the user presses or releases keyboard keys.
 The Java KeyListener is notified whenever you change the state of key.
It is notified against KeyEvent.
 The KeyListener interface is found in java.awt.event package.

 It has three methods.


1. public abstract void keyPressed(KeyEvent e) : Invoked when a key
has been pressed.
2. public abstract void keyReleased(KeyEvent e) : Invoked when a
key has been released.
3. public abstract void keyTyped(KeyEvent e) : Invoked when a key
has been typed.
 Example:- public void keyPressed(KeyEvent e)
{
import java.awt.*; l.setText("Key Pressed");
import java.awt.event.*; }
class Mykey extends Frame implements public void keyReleased(KeyEvent e)
KeyListener {
{ l.setText("Key Released");
Label l; }
TextArea t; public void keyTyped(KeyEvent e)
Mykey() {
{ l.setText("Key Typed");
l = new Label(""); }
l.setBounds(20, 40, 150, 20); }
t = new TextArea(); public class MyKeyEvent
t.setBounds(20, 100, 150, 50); {
add(l); public static void main(String[] args)
add(t); {
setLayout(null);
Mykey a = new Mykey();
setSize(300,300);
}
setVisible(true);
}
t.addKeyListener(this);
}
 Output :-
FOCUSEVENT CLASS
 This event indicates that a Component has gained or lost the input
focus.
 This event is generated by a Component (such as a TextField,etc).
 The event is passed to every FocusListener which registered to receive
such events using the Component's addFocusListener method.
 Each such listener object gets this FocusEvent when the event occurs.
 The FocusListener has following methods:-
1. void focusGained(FocusEvent e) : Invoked when a component
gains the keyboard focus.
2. void focusLost(FocusEvent e) : Invoked when a component loses
the keyboard focus.
 Example :- add(l1);
import java.awt.*; add(l2);
import java.awt.event.*; add(t1);
add(t2);
class MyFocus extends Frame implements add(b);
FocusListener setLayout(null);
{ setSize(300,300);
Label l1, l2; setVisible(true);
TextField t1,t2;
Button b; t1.addFocusListener(this);
MyFocus() t2.addFocusListener(this);
{ b.addFocusListener(this);
l1 = new Label(""); }
l1.setBounds(20, 40, 150, 20); public void focusGained(FocusEvent fe)
l2 = new Label(""); {
l2.setBounds(20, 60, 150, 20); l1.setText(fe.getComponent().getName() +
t1 = new TextField(20); "GetFocus");
t1.setBounds(20, 80, 150, 20); }
t2 = new TextField(20); public void focusLost(FocusEvent fe)
t2.setBounds(20, 100, 150, 20); {
b = new Button("Click Here"); l2.setText(fe.getComponent().getName() +
b.setBounds(20, 120, 150, 20); "GetLost");
}
}
public class MyFocusEvent
{
public static void main(String[] args)
{
MyFocus a = new MyFocus();
}
}

 Output:-
ITEMEVENT CLASS
 The Java ItemListener is notified whenever you click on the checkbox.
 It is notified against ItemEvent.
 The ItemListener interface is found in java.awt.event package.
 It has only one method: itemStateChanged().
 The itemStateChanged() method is invoked automatically whenever
you click or unclick on the registered checkbox component.

public abstract void itemStateChanged(ItemEvent e);


 Example:- c1.addItemListener(this);
import java.awt.*; c2.addItemListener(this);
import java.awt.event.*; }
public void itemStateChanged(ItemEvent e)
class MyItem extends Frame implements ItemListener { if(e.getSource()==c1)
{ {
Label l; l.setText("C++ Checkbox: " +
Checkbox c1,c2; (e.getStateChange()==1?"checked":"unchecked"));
}
MyItem()
else
{
{
l = new Label();
l.setText("Java Checkbox: " +
l.setBounds(20,50,200,50);
(e.getStateChange()==1?"checked":"unchecked"));
c1 = new Checkbox("C++");
}
c1.setBounds(100,100, 100,50);
}
c2 = new Checkbox("Java");
}
c2.setBounds(100,150, 100,50);
public class MyItemEvent
add(c1);
{
add(c2);
public static void main(String[] args)
add(l);
{
setSize(400,400);
MyItem a = new MyItem();
setLayout(null);
}
setVisible(true);
}
setTitle("ItemEvent Example");
 Output:-
TEXTEVENT CLASS
 An event of type TextEvent is generated when a value in textfield or
textarea is entered or edited. A class that wants to listen and respond to
an event of type TextEvent, must implement
the TextListener interface.

 It should implement an interface, TextListener and provide


implementation of its methods :

1. public void textValueChanged(TextEvent e) :This method is called


when a value in textfield or textarea is entered or edited.
 Example:- public void textValueChanged(TextEvent te)
import java.awt.*; {
import java.awt.event.*; l.setText("Text Changed");
class MyText extends Frame implements TextListener }
{ }
Label l; public class MyTextEvent
TextField t; {
MyText() public static void main(String[] args)
{ {
l = new Label(); MyText a = new MyText();
l.setBounds(20, 50, 100, 20); }
t = new TextField(25); }
t.setBounds(20, 100, 100, 20);  Output :-

add(l);
add(t);

setSize(300,300);
setLayout(null);
setVisible(true);
setTitle("TextEvent Example");

t.addTextListener(this);
}
WINDOWEVENT CLASS
 The object of this class represents the change in state of a window.
 This low-level event is generated by a Window object when it is
opened, closed, activated, deactivated, or when focus is transferred into
or out of the Window.
 The signature of 7 methods found in WindowListener interface are
given below :-
 public abstract void windowActivated(WindowEvent e);
 public abstract void windowClosed(WindowEvent e);
 public abstract void windowClosing(WindowEvent e);
 public abstract void windowDeactivated(WindowEvent e);
 public abstract void windowDeiconified(WindowEvent e);
 public abstract void windowIconified(WindowEvent e);
 public abstract void windowOpened(WindowEvent e);
 Example :- public void windowDeactivated(WindowEvent
import java.awt.*; we)

import java.awt.event.*; { System.out.println("deactivated"); }

class MyWindow extends Frame implements


WindowListener public void windowDeiconified(WindowEvent
{ we)

MyWindow() { System.out.println("deiconified"); }

{ addWindowListener(this);
setSize(400,400); public void windowIconified(WindowEvent
we)
setLayout(null);
{ System.out.println("iconified"); }
setVisible(true);
}
public void windowOpened(WindowEvent we)
public void windowActivated(WindowEvent
we) { System.out.println("opened"); }

{ System.out.println("activated"); } }
public class MyWindowEvent

public void windowClosed(WindowEvent we) {

{ System.out.println("closed"); } public static void main(String[] args)


{

public void windowClosing(WindowEvent we) MyWindow a = new MyWindow ();

{ System.out.println("closing"); }

dispose(); } }
ADAPTER CLASS
 Java adapter classes provide the default implementation of
listener interfaces.
 If you inherit the adapter class, you will not be forced to provide the
implementation of all the methods of listener interfaces.
 So it saves code. The Adapter classes with their corresponding listener
interfaces are given below.

Adapter class Listener interface

WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
 WindowAdapter Example :-

import java.awt.*;
import java.awt.event.*;
class MyWindow extends Frame
{ MyWindow()
{
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ dispose(); }
});
setSize(400,400);
setLayout(null);
setVisible(true);
}
}
public class MyWindowEvent
{
public static void main(String[] args)
{
MyWindow a = new MyWindow();
}
}
 KeyAdapter Example:- a.addKeyListener(new KeyAdapter()
{
import java.awt.*; public void keyTyped(KeyEvent ke)

import java.awt.event.*; {

class MyKey extends Frame l.setText("Key Typed");


}
{
});
Label l;
}
MyKey()
}
{
public class MyKeyEvent
l = new Label();
{
l.setBounds(20,40,150,30);
public static void main(String[] args)
TextArea a = new TextArea(); {
a.setBounds(20,80,150,80); MyKey a = new MyKey();
}
add(l); }
add(a);
setLayout(null);
setSize(400,400);
setVisible(true);

You might also like