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

Unit-2-UI

The document provides an overview of Java's GUI frameworks, specifically AWT and Swing, highlighting their differences, components, and usage. AWT is described as a heavyweight, platform-dependent framework, while Swing is lightweight, platform-independent, and offers a richer set of components. Additionally, it covers key GUI elements such as containers, components, layout managers, and examples of creating various GUI components like JFrame, JLabel, JTextField, and JButton.

Uploaded by

elviezan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Unit-2-UI

The document provides an overview of Java's GUI frameworks, specifically AWT and Swing, highlighting their differences, components, and usage. AWT is described as a heavyweight, platform-dependent framework, while Swing is lightweight, platform-independent, and offers a richer set of components. Additionally, it covers key GUI elements such as containers, components, layout managers, and examples of creating various GUI components like JFrame, JLabel, JTextField, and JButton.

Uploaded by

elviezan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 102

Unit – 2

User Interface Components with


Swing

BSc CSIT 7th Semester

2024
1

Dabbal Singh Mahara


Java AWT
• The Abstract Window Toolkit (AWT) was Java’s first GUI framework.
• A GUI component is an object with which the user interacts via the mouse,
the keyboard or another form of input, such as voice recognition.
• Java AWT is an API to develop GUI or window-based applications in java.
• AWT contains large number of classes and methods that allows us to create
and manage graphical user interface (GUI) applications, such as windows,
buttons, scroll bars, etc.
• The AWT classes are contained in the java.awt package.

2
Swing
• Swing is a framework that provides more powerful and flexible GUI
components than does the AWT. As a result, it is the GUI that has been
widely used by Java programmers
• Swing API is a set of extensible GUI components to ease developers
life to create java based Front End /GUI applications.
• It is built upon top of AWT API and acts as replacement of AWT API
as it has almost every control corresponding to AWT control.
• Swing is a light weight, offers rich controls and highly customizable.
• The Swing GUI components are defined in the javax.swing package.

3
awt vs swing
• The basic difference is that awt is heavy weight and swing is light weight.
• Heavy weight means that when you're using the awt components, the
native code used for getting view for the component is generated by the
Operating System, that's why the look and feel changes from OS to OS.
• Where as in swing components its the responsibility of JVM to generate
the view for the components.
• AWT components are platform-dependent. Swing components are
platform-independent.
• swing is MVC based and awt is not

4
awt vs swing
No. Java AWT Java Swing
1) AWT components are platform-dependent. Java swing components are platform-independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable look and Swing supports pluggable look and feel.
feel.
4) AWT provides less components than Swing. Swing provides more powerful components such as
tables, lists, scrollpanes, colorchooser, tabbedpane etc.
5) AWT doesn't follows MVC(Model View Swing follows MVC.
Controller) where model represents data,
view represents presentation and controller
acts as an interface between model and
view.

5
java Containers and Components
• There are two types of GUI elements:
• Component: Components are elementary GUI entities, such as Button, Label, and
TextField.
• Container: Containers are used to hold components in a specific layout .
Examples: Frame and Panel,.
• A container can also hold sub-containers.

6
Javax.swing
Components

7
Swing UI elements

8
java Containers and Components
• A Frame is the top-level container of an AWT program. A Frame has a title bar
(containing an icon, a title, and the minimize/maximize/close buttons), an optional
menu bar and the content display area.
• A Panel is a rectangular area used to group related GUI components in a certain
layout.
• There are five components: a Label (providing description), a TextField (for users to
enter text), and three Buttons (for user to trigger certain programmed actions).
• In a GUI program, a component must be kept in a container. You need to identify a
container to hold the components. Every container has a method called
add(Component c).
• Example: JFrame fr = new JFrame();
JButton btn = new JButton("Save");
fr.add(btn);
9
Swing's Top Level Containers
• JFrame: used for the application's main window (with an icon, a title,
minimize/maximize/close buttons, an optional menu-bar, and a content-pane), as
illustrated.
• JDialog: used for secondary pop-up window (with a title, a close button, and a
content-pane).
• JApplet: used for the applet's display-area (content-pane) inside a browser’s
window.
• The JComponents must be added onto the so-called content-pane of the top-level
container. Content-pane is in fact a java.awt.Container that can be used to group
and layout components.

10
JFrame
• A Swing frame is a container that functions as the main window for programs that use Swing
components.
• Swing frames possess a title, a border and buttons for iconifying, maximizing, and closing the
frame.
• Swing provides the JFrame class that is a part of the javax.swing package.
• We create JFrame as: JFrame frame = new JFrame();
• By default a frame is invisible, so we make it visible using method: frame.setVisible(true);
• The frame will have no height no width, we can maximize manually.
• Instead of creating objects from JFrame directly, we can create frames by extending JFrame class
with our own class.
class MyFrame extends Jframe {
public static void main(String [] args) {
MyFrame frame = new MyFrame();
}
} 11
JFrame
• JFrame is top level container in java. It contains other java GUI components.
JFrame frame = new JFrame();
• Methods:
1. frame.setVisible(true);
2. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
3. frame.setSize(width, height);
4. frame.setLocation(x, y);
5. frame.setBounds(x, y,width,height);
6. frame.setTitle("Frame Title");
7. frame.setIconImage(icon.getImage()); // ImageIcon icon = new ImageIcon("logo.gif");

12
JFrame Example
//f.setSize(500,400);
//creating JFrame
//jf.setLocation(150,100);
import javax.swing.*;
f.setBounds(100,100,1000,500);
import java.awt.*; f.setTitle("My First Frame");
class MyFirstFrame { ImageIcon icon = new
ImageIcon("icon.png");
public static void main(String[] args) {
f.setIconImage(icon.getImage());
JFrame f = new JFrame(); Container c = jf.getContentPane();
f.setVisible(true); c.setBackground(Color.blue);
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); f.setResizable(false);

}
}

13
JFrame's Content-Pane
• The JFrame's method getContentPane() returns the content-pane (which is
a java.awt.Containter) of the JFrame. You can then set its layout (the
default layout is BorderLayout), and add components into it.
• For example,
Container cp = getContentPane(); // Get the content-pane of this JFrame
cp.setLayout(new FlowLayout()); // content-pane sets to FlowLayout
cp.add(new JLabel("Counter")); // content-pane adds a JLabel component
......
cp.add(tf); // content-pane adds a JTextField component
......
cp.add(btnCount); // content-pane adds a JButton component

14
Adding Components to Container
• get the content-pane via getContentPane() from a top-level container, and add
components onto it.
• For example,
public class SwingDemo extends JFrame {
// Constructor
public SwingDemo() {
// Get the content-pane of this JFrame, which is a java.awt.Container
// All operations, such as setLayout() and add() operate on the content-pane
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(new JLabel("Hello, world!"));
cp.add(new JButton("Button"));
......
}
.......
15
}
Creating JLabel
• A typical GUI consists of many components.
• GUI designers often provide text stating the purpose of each
components. Such text is known as a label and is created with a
JLabel—a subclass of JComponent.
• A JLabel displays read-only text, an image, or both text and an
image.
• Applications rarely change a label’s contents after creating it.

16
Example: 1
//creating JLabel Container c = jf.getContentPane();
import javax.swing.*; c.setLayout(null);

import java.awt.*;
JLabel label = new JLabel("Username");
label.setText("Sign in");
class MyLabel { c.add(label);
public static void main(String[] args) { label.setBounds(100,100,100,30);
JFrame jf = new JFrame();
jf.setVisible(true); Font f = new Font("Arial",Font.BOLD,20);
label.setFont(f);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
jf.setBounds(100,100,1000,500);
}

17
Example:
import java.awt.*; Container c = frame.getContentPane();
import javax.swing.*; c.setLayout(null);
class MyImageLabel { ImageIcon icon = new
public static void main(String[] args) { ImageIcon("icon.png");
JFrame frame = new JFrame(); JLabel label = new JLabel(icon);
frame.setVisible(true);
label.setBounds(100,50,icon.getIconWi
dth(),icon.getIconHeight());
frame.setDefaultCloseOperation(JFrame
.EXIT_ON_CLOSE); c.add(label);
frame.setBounds(100,200,500,1000); }}

18
JTextField
• A text field is a basic text control that lets the user enter a small
amount of text.
• Generally used with GUI based data entry screens in commercial
application or Applets.
• Text fields are implemented in Swing by the JTextField class.

19
Example: JTextField
Container c = fr.getContentPane();
//TextFields
c.setLayout(null);
import javax.swing.*;
JTextField mytext = new JTextField();
import java.awt.*;
mytext.setBounds(100,50, 200,40);
c.add(mytext);
class MyTextField {
public static void main(String[] args) { Font f = new Font("Arial",Font.ITALIC,25);
JFrame fr = new JFrame(); mytext.setFont(f);
fr.setVisible(true); mytext.setBackground(Color.YELLOW);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLO mytext.setForeground(Color.RED);
SE); // Color clr = new Color(120,100,50);
fr.setBounds(100,100,1000,500); // mytext.setBackground(clr);
} }
20
PasswordField: Example
Container c = fr.getContentPane();
//TextFields
c.setLayout(null);
import javax.swing.*;
JPasswordField pass = new JPasswordField();
import java.awt.*;
pass.setBounds(100,50, 150,40);
c.add(pass);
class MyPasswordField {
Font f = new Font("Arial",Font.ITALIC,25);
public static void main(String[] args) {
pass.setFont(f);
JFrame fr = new JFrame();
fr.setVisible(true);
pass.setBackground(Color.YELLOW);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_C
LOSE); pass.setForeground(Color.RED);
fr.setBounds(100,100,1000,500); // Color clr = new Color(120,100,50);
// pass.setBackground(clr);
}} 21
JButton

• A button is a GUI component the user clicks to trigger a specific


action.
• A Java application can use several types of buttons, including
command buttons, checkboxes, toggle buttons and radio buttons.
• A command button generates an ActionEvent when the user clicks it.
• Command buttons are created with class JButton.
• The text on the face of a JButton is called a button label.
• A GUI can have many JButtons, but each button label should be
unique in the portion of the GUI that’s currently displayed.
• JButton is also in javax.swing package only.
22
JButton

• Create JButton as: JButton btn = new JButton();


• Whenever we create buttons, buttons will be created separately and
Frame will be separate. So, we need to add button to the Frame.
• Adding button to the frame: frame.add(btn);
• By default, button will occupy whole frame. We need to manage its
layout. It is done by using Layout manager either by predefined
layouts or user-defined layout.

23
JButton
//JButton //JButton btn = new JButton("Save");
import javax.swing.*; JButton btn = new JButton();
import java.awt.*; btn.setBounds(100,50, 200,40);
c.add(btn);
class MyButton {
public static void main(String[] args) { btn.setText("Click Me");
JFrame fr = new JFrame();
fr.setVisible(true); Font f = new Font("Arial",Font.ITALIC,25);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) btn.setFont(f);
;
fr.setBounds(100,100,1000,500);
}
}
Container c = fr.getContentPane();
c.setLayout(null);

24
Image on the Jbutton
//JButton c.setLayout(null);
import javax.swing.*; ImageIcon icon = new ImageIcon("logo.png");
import java.awt.*; JButton btn = new JButton(icon);
btn.setBounds(100,50,100,50);
class MyButton2 { // btn.setBounds(100,50,
icon.getIconWidth(),icon.getIconHeight());
public static void main(String[] args) {
JFrame fr = new JFrame(); c.add(btn);

fr.setVisible(true); Cursor cur = new


Cursor(Cursor.HAND_CURSOR);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btn.setCursor(cur);
fr.setBounds(100,100,1000,500);
}
Container c = fr.getContentPane();
}
25
Layout Managers
• Layout managers arrange GUI components in a container for
presentation purpose.
• You can use the layout managers for basic layout capabilities instead
of determining every GUI component's exact position and size.
• All layout managers implement the interface LayoutManager (in
package java.awt).
• Class Container’s setLayout method takes an object that implements
the LayoutManager interface as an argument.

26
Absolute positioning

• This provides the greatest level of control over a GUI’s


appearance.
• By setting a Container’s layout to null, you can specify the
absolute position of each GUI component with respect to the
upper-left corner of the Container by using Component
methods setSize and setLocation or setBounds.

27
Layout managers
• Using layout managers to position elements can be simpler and faster
than creating a GUI with absolute positioning, but you lose some
control over the size and the precise positioning of GUI components.

28
FlowLayout
• FlowLayout is the simplest layout manager.
• GUI components are placed on a container from left to right in the
order in which they’re added to the container. When the edge of the
container is reached, components continue to display on the next line.
• Class FlowLayout allows GUI components to be left aligned, centered
(the default) and right aligned.
• The constructors for FlowLayout:
FlowLayout( )
FlowLayout(int align)
FlowLayout(int align, int horz, int vert)
29
FlowLayout
• The first form creates the default layout, which centers components and leaves five pixels
of space between each component.
• The second form lets you specify how each line is aligned. Valid values for align are as
follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout.LEADING
FlowLayout.TRAILING
• These values specify left, center, right, leading edge, and trailing edge alignment,
respectively.
• The third constructor allows you to specify the horizontal and vertical space left between
components in horz and vert, respectively

30
Example: FlowLayout
// import statements // adding the buttons to frame
import java.awt.*; f.add(b1);f.add(b2);f.add(b3);f.add(b4);
import javax.swing.*; f.add(b5);f.add(b6); f.add(b7); f.add(b8);
public class FlowLayoutExample { f.add(b9); f.add(b10);
JFrame f; // parameter less constructor is used
// constructor // therefore, alignment is center
FlowLayoutExample() { // horizontal as well as the vertical gap is 5 units.
// creating a frame object f.setLayout(new FlowLayout());
f = new JFrame(); f.setSize(300, 300);
// creating the buttons f.setVisible(true);
JButton b1 = new JButton("button1"); f.setTitle("Flow Layout Example");
JButton b2 = new JButton("button2"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b3 = new JButton("button3"); }
JButton b4 = new JButton("button4");
JButton b5 = new JButton("button5"); // main method
JButton b6 = new JButton("button6"); public static void main(String argvs[]) {
JButton b7 = new JButton("button7"); new FlowLayoutExample();
JButton b8 = new JButton("button8"); }
JButton b9 = new JButton("button9"); }
JButton b10 = new JButton("button10");
31
Output

32
BorderLayout
• The BorderLayout layout manager (the default layout manager for a
JFrame) arranges components into five regions: NORTH, SOUTH, EAST,
WEST and CENTER.
• A BorderLayout limits a Container to containing at most five
components—one in each region.
• The components placed in the NORTH and SOUTH regions extend
horizontally to the sides of the container and are as tall as the components
placed in those regions.
• The EAST and WEST regions expand vertically between the NORTH and
SOUTH regions and are as wide as the components placed in those
regions.
• The component placed in the CENTER region expands to fill all remaining
space in the layout .
33
BorderLayout
• If all five regions are occupied, the entire container’s space is covered
by GUI components.
• If the NORTH or SOUTH region is not occupied, the GUI components in
the EAST, CENTER and WEST regions expand vertically to fill the
remaining space.
• If the EAST or WEST region is not occupied, the GUI component in the
CENTER region expands horizontally to fill the remaining space.
• If the CENTER region is not occupied, the area is left empty—the other
GUI components do not expand.

34
BorderLayout

35
BorderLayout
Here are the constructors defined by BorderLayout:
BorderLayout( )
BorderLayout(int horz, int vert)
The first form creates a default border layout. The second allows you to specify the horizontal
and vertical space left between components in horz and vert, respectively.
BorderLayout defines the following constants that specify the regions:
BorderLayout.CENTER
BorderLayout.SOUTH
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.NORTH

When adding components, you will use these constants with the following form of add( ),
which is defined by Container:
void add(Component compRef, Object region)
Here, compRef is a reference to the component to be added, and region specifies where the
component will be added.
36
Example: BorderLayout
import java.awt.*;
import javax.swing.*; f.setSize(300, 300);
public class BorderLayoutDemo { f.setTitle("Border Layout Demo");
JFrame f; f.setVisible(true);
BorderLayoutDemo() { }
f = new JFrame(); public static void main(String[] args) {
// creating buttons new BorderLayoutDemo();
JButton b1 = new JButton("Button1");; // the button will be labeled as NORTH
}
JButton b2 = new JButton("Button2");; // the button will be labeled as SOUTH
}
JButton b3 = new JButton("Button3");; // the button will be labeled as EAST
JButton b4 = new JButton("Button4");; // the button will be labeled as WEST
JButton b5 = new JButton("Button5");; // the button will be labeled as CENTER
f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center

37
Output

38
GridLayout
• The GridLayout layout manager divides the container into a grid so
that components can be placed in rows and columns.
• Class GridLayout inherits directly from class Object and implements
interface LayoutManager.
• Every Component in a GridLayout has the same width and height.
Components are added to a GridLayout starting at the top-left cell of
the grid and proceeding left to right until the row is full.
• Then the process continues left to right on the next row of the grid,
and so on.

39
GridLayout
The constructors supported by GridLayout are shown here:
GridLayout( )
GridLayout(int numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int vert)
The first form creates a single-column grid layout.
The second form creates a grid layout with the specified number of rows and columns.
The third form allows you to specify the horizontal and vertical space left between
components in horz and vert, respectively. Either numRows or numColumns can be zero.
Specifying numRows as zero allows for unlimited-length columns.

40
Example: GridLayout
import java.awt.*;
import javax.swing.*; f.add(b1); f.add(b2); f.add(b3);
public class MyGridLayout{ f.add(b4); f.add(b5); f.add(b6);
JFrame f; f.add(b7); f.add(b8); f.add(b9);
MyGridLayout(){ // setting grid layout of 3 rows and 3 columns
f=new JFrame(); f.setLayout(new GridLayout(3,3));
JButton b1=new JButton("1"); f.setSize(300,300);
JButton b2=new JButton("2"); f.setTitle("Grid Layout Demo");
JButton b3=new JButton("3"); f.setVisible(true);
JButton b4=new JButton("4");
JButton b5=new JButton("5"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b6=new JButton("6"); }
JButton b7=new JButton("7"); public static void main(String[] args) {
JButton b8=new JButton("8");
new MyGridLayout();
JButton b9=new JButton("9");
}
// adding buttons to the frame
}
41
Output

42
Event Handling
• When the user interacts with a GUI component, the interaction is
known as an event and it drives the program to perform a task.
• Some common user interactions that cause an application to perform
a task include clicking a button, typing in a text field, selecting an
item from a menu, closing a window and moving the mouse.
• The code that performs a task in response to an event is called an
event handler, and the overall process of responding to events is
known as event handling.
• Event Handling is the mechanism that controls the event and decides
what should happen if an event occurs.

43
Components of Event Handling

• There are three main components in Event Handling.


• They are:
➢ Events : An event is a change in state of an object.
➢ Events Source : Event source is an object that generates an
event.
➢ Listeners : A listener is an object that listens to the event. A
listener gets notified when an event occurs.
• Events occurs when the user communicates with the
Graphical User Interface. All the events are listened by the
event listeners.

44
The Delegation Event Model
• The basic idea is,
• A source generates an event and sends it to one or more
listeners.
• The listener simply waits until it receives an event. Once
an event is received, the listener processes the event and
then returns.
• The Delegation Event Model has the following key participants
namely:
➢ Event Source
➢ Event Listener
45
Event Source
• The source is an object on which event occurs.
• Source is responsible for providing information of the occurred event
to it's handler.
• This occurs when the internal state of that object changes in some
way. Sources may generate more than one type of event.
• A source must register listeners in order for the listeners to receive
notifications about a specific type of event.

46
Event Listener
• Event Listener - It is also known as event handler.
• Listener is responsible for generating response to an event.
• A listener is an object that is notified when an event occurs.
• Listener waits until it receives an event. Once the event is received , the
listener processes the event an then returns.
• Listener has two major requirements.
➢ First, it must have been registered with one or more sources to receive
notifications about specific types of events.
➢ Second, it must implement methods to receive and process these notifications.

47
Event Handling Model

48
Steps involved in event handling
• The User clicks the button and the event is generated.
• Now the object of concerned event class is created automatically and
information about the source and the event get populated with in
same object.
• Event object is forwarded to the method of registered listener class.
• The method is now get executed and returns.

49
Advantage of The Delegation Model
• The benefit of this approach is that the user interface logic is
completely separated from the logic that generates the event.
• The user interface element is able to delegate the processing of an
event to the separate piece of code.
• In this model ,Listener needs to be registered with the source object
so that the listener can receive the event notification. This is an
efficient way of handling the event because the event notifications
are sent only to those listener that want to receive them.

50
Types of Events and Listeners
• Java has provided predefined library for event hanlding as a package:
java.awt.event
GUI Component Event Name Listener Listener Methods
Button / Menu ActionEvent ActionListener public void actionPerformed(ActionEvent e)

public void focusGained(FocusEvent fe)


TextField / TextArea FocusEvent FocusListener
public void focusLost(FocusEvent fe)

CheckBox / List/
ItemEvent ItemListener public void itemStateChanged(ItemEvent ie)
RadioButton
public void adjustmentValueChanged(
ScrollBar AdjustmentEvent AdjustmentListener
AdjustmentEvent ae)

51
Types of Events and Listeners
GUI Component Event Name Listener Listener Methods
Window WindowEvent WindowListener public void windowOpened(WindowEvent we)
public void windowClosed(WindowEvent we)
public void windowClosing(WindowEvent we)
public void windowIconified(WindowEvent we)
public void windowDeiconified(WindowEvent we)
public void windowActivated(WindowEvent we)
public void windowDeactivated(WindowEvent we)

Mouse MouseEvent MouseListener public void mouseClicked(MouseEvent me)


public void mousPressed(MouseEvent me)
public void mouseReleased(MouseEvent me)
public void mouseEntered(MouseEvent me)
public void mouseExited(MouseEvent me)
Keyboard KeyEvent KeyListener public void keyPressed(KeyEvent ke)
public void keyReleased(KeyEvent ke)
public void keyTyped(KeyEvent ke) 52
Handling ActionEvent
• ActionEvent occurs when a user
• clicks a button
• chooses a menu item
• Presses enter in a textfield
• To handle ActionEvent there is an interface ActionListener.
• Follow these three steps to handle ActionEvent:
1. implement this interface
2. Override the method to write event handling code
public void actionPerformed(ActionEvent e) { }
3. Register the event source with actionListener using:
src.addActionListener(ActionEvent ObjectReference); 53
ActionEvent Handling : for JButton
import javax.swing.*; public void actionPerformed(ActionEvent e) {
import java.awt.*; c.setBackground(Color.YELLOW);
import java.awt.event.*;
} }

class Frame1 extends JFrame implements ActionListener {


JButton btn = new JButton("Click"); class ActionDemo {
Container c; public static void main(String[] args) {
Frame1() { Frame1 fr = new Frame1();
c = this.getContentPane(); fr.setVisible(true);
c.setLayout(null);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setBounds(100,100,1000,500);
btn.setBounds(100,50,100,50);
btn.addActionListener(this); }
}
c.add(btn);
}
54
Example -2: ActionEvent Handling
c.add(btn1);
import java.awt.*; c.add(btn2);
import javax.swing.*; c.add(btn3);
import java.awt.event.*; }
class EventFrame2 extends JFrame implements public void actionPerformed(ActionEvent e) {
ActionListener { if(e.getSource()== btn1)
c.setBackground(Color.RED);
JButton btn1 = new JButton("Action 1"); if(e.getSource()== btn2)
JButton btn2 = new JButton("Action 2"); c.setBackground(Color.GREEN);
JButton btn3 = new JButton("Action 3"); if(e.getSource()==btn3)
Container c; c.setBackground(Color.YELLOW);
EventFrame2() { }
c = this.getContentPane(); }
c.setLayout(null); class EventDemo2 {
btn1.setBounds(50,100,100,50); public static void main(String[] args) {
btn2.setBounds(50,200,100,50); EventFrame2 fr = new EventFrame2();
btn3.setBounds(50,300,100,50); fr.setVisible(true);
btn1.addActionListener(this); fr.setBounds(50,50,500,500);
btn2.addActionListener(this); fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btn3.addActionListener(this); }}

55
Example-3: ActionEvent in TextField
import javax.swing.*;
import java.awt.*; c.add(tf);
import java.awt.event.*; Font f = new Font("Arial",Font.BOLD, 20);
class ActionEventTextField extends JFrame implements
tf.setFont(f);
ActionListener {
JTextField tf = new JTextField(); }
ActionEventTextField() { public void actionPerformed(ActionEvent e) {
this.setVisible(true); String str = tf.getText();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); String ntxt = str.toUpperCase();
this.setBounds(50,50,500,500);
tf.setText(ntxt);
this.setTitle("TextField ActionEvent");
}
Container c = this.getContentPane();
c.setLayout(null); public static void main(String[] args) {
tf.setBounds(20,20,80,30); ActionEventTextField obj = new
ActionEventTextField();
tf.addActionListener(this);
} }
56
JRadioButton
• Radio buttons are a group of mutually exclusive buttons, in which only one
button can be selected at any one time.
• The JRadioButton class is used to create a radio button.
• It is used to choose one option from multiple options. It is widely used in exam
systems or quiz.
• It should be added in ButtonGroup to select one radio button only.
• JRadioButton provides different constructors some are:
• JRadioButton() : Creates an unselected radio button with no text.
• JRadioButton(String s): Creates an unselected radio button with specified
text.
• JRadioButton(String s, boolean selected) : Creates a radio button with the
specified text and selected status.

57
JRadioButton
▪ In order for their mutually exclusive nature to be activated, radio
buttons must be configured into a group. Only one of the buttons in
the group can be selected at any time. For example, if a user
presses a radio button that is in a group, any previously selected
button in that group is automatically deselected.
• A button group is created by the ButtonGroup class. Its default
constructor is invoked for this purpose. Elements are then added to
the button group via the following method:
void add(AbstractButton ab)
Here, ab is a reference to the button to be added to the group.

58
Commonly used Methods
Methods Description
void setText(String s) It is used to set specified text on button.
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void addActionListener ( It is used to add the action listener to this object
ActionListener a)

59
Example: RadioButton
import javax.swing.*; radio1.setBounds(50,50,70,50);
import java.awt.*; JRadioButton radio2 = new
class MyRadio { JRadioButton("Feamle");
public static void main(String[] args) { radio2.setBounds(120,50, 100, 50);
JFrame frame = new JFrame();
ButtonGroup gender= new ButtonGroup();
frame.setVisible(true);
gender.add(radio1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON gender.add(radio2);
_CLOSE);
frame.setBounds(50,50,500,500); radio1.setSelected(true);
Container c = frame.getContentPane(); //radio1.setEnabled(false);
c.setLayout(null); c.add(radio1);
JRadioButton radio1 = new JRadioButton("Male");
c.add(radio2);
} }
60
JCheckBox
• Check boxes are similar to radio buttons but their selection model is
different, by convention.
• Any number of check boxes in a group — none, some, or all — can be
selected.
• A group of radio buttons, on the other hand, can have only one button
selected.
• Commonly used methods:
• setIcon(Icon i) : sets the icon of the checkbox to the given icon
• setText(String s) :sets the text of the checkbox to the given text
• setSelected(boolean b) : sets the checkbox to selected if boolean value passed is
true or vice versa
• getIcon() : returns the image of the checkbox
• getText() : returns the text of the checkbox
61
Example: CheckBox
import javax.swing.*; JCheckBox check2 = new JCheckBox("DotNet");
import java.awt.*; check2.setBounds(50,80, 100,50);
class MyCheckBox { JCheckBox check3 = new JCheckBox("Python");
public static void main(String[] args) { check3.setBounds(50,110, 100,50);
JFrame frame = new JFrame();
frame.setVisible(true); c.add(check1);
frame.setDefaultCloseOperation( c.add(check2);
JFrame.EXIT_ON_CLOSE); c.add(check3);
frame.setBounds(50,50,500,500);
Container c = frame.getContentPane();
check1.setSelected(true);
c.setLayout(null);
JCheckBox check1 = new JCheckBox ("Core Java"); //check1.setEnabled(false);
check1.setBounds(50,50,100,50); } }

62
JComboBox
• A combo box (sometimes called a drop-down list) enables the user to select one item from a list.
• Combo boxes are implemented with class JComboBox, which extends class JComponent.
• JComboBox can be editable or read- only depending on the choice of the programmer .
• Example:
String [] a = {"Pig", "Bird", "Cat", "Dog", "Rabit"}
JComboBox cb1 = new JComboBox(a);

some methods:
• cb1.setEditable(true);
• cb1.setSelectedIndex(2);
• cb1.setSelectedItem("Pig");
• cb1.addItem("Cow");
• cb1.insertItemAt("Fox",2);
• cb1.removeItem("Bird");

63
JTextArea
• It represents a multi line area that displays text. It is used to edit the text .
• Constructors:
• JTextArea() : constructs a new blank text area .
• JTextArea(String s) : constructs a new text area with a given initial text.
• JTextArea(int row, int column) : constructs a new text area with a given number of
rows and columns.
• JTextArea(String s, int row, int column) : constructs a new text area with a given
number of rows and columns and a given initial text.
• Example:
JTextArea ta =new JTextArea();
ta.setBounds(10,30, 200,200);

64
Example: label2 = new JLabel("Characters:");
import javax.swing.*; label2.setBounds(50,100,150,20);
import java.awt.*; btn = new JButton("Count");
import java.awt.event.*; btn.setBounds(100,250,100,30);
class MyTextAreaDemo implements ActionListener {
JLabel label1,label2; btn.addActionListener(this);
JTextArea ta;
c.add(label1);
JButton btn;
c.add(label2);
Container c;
c.add(ta);
MyTextAreaDemo() { c.add(btn);
JFrame fr = new JFrame("TextArea Demonstration"); c.revalidate(); // instructs LayoutManager to recalculate layout
fr.setBounds(50,50,600,600); }
fr.setVisible(true);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); public void actionPerformed(ActionEvent e) {
c = fr.getContentPane(); String text=ta.getText();
c.setLayout(null); String words[]=text.split("\\s");
label1.setText("Words: "+words.length);
ta = new JTextArea("This is my text area.");
label2.setText("Characters: "+text.length());
ta.setBounds(300,50,200,250);
}
ta.setEditable(true); public static void main(String[] args) {
ta.setFont(new Font("Serif", Font.ITALIC, 16)); MyTextAreaDemo t = new MyTextAreaDemo();
ta.setLineWrap(true); }
ta.setWrapStyleWord(true); }
label1 = new JLabel("Words:"); 65
label1.setBounds(50,50,100,40);
JList
• A list displays a series of items from which the user may select one
or more items .
• Lists are created with class JList, which directly extends class
JComponent.
• Class JList supports single selection lists (which allow only one item
to be selected at a time) and multiple-selection lists(which allow any
number of items to be selected).
• Example:
String [] arr = {"black", "blue", "red", "yellow"};
JList l = new JList(arr);

66
Set Selection Mode for JList
• The selection mode defines the way elements can be selected. There are totally 3
selection modes available to be set for JList:
• SINGLE_SELECTION:
This mode specifies that only a single item can be selected at any point of time.
• SINGLE_INTERVAL_SELECTION:
This mode specifies that multiple items can be selected, but they have to be
contiguous. Items can be selected contiguously by pressing down the shift key
and selecting elements with the mouse.
• MULTIPLE_INTERVAL_SELECTION:
This mode is the default mode. This mode specifies that multiple items can be
selected and they may or may not be contiguous.
• Eg: list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

67
JList Methods:
• getSelectedIndex() : returns the index of selected item of the list
• getSelectedValue() : returns the selected value of the element of the list
• setSelectedIndex(int i) : sets the selected index of the list to i
• setSelectionBackground(Color c) : sets the background Color of the list
• setSelectionForeground(Color c) : Changes the foreground color of the list
• setVisibleRowCount(int v) : Changes the visibleRowCount property
• setFixedCellWidth(int w) Changes the cell width of list to the value passed as parameter.
• setFixedCellHeight(int h) : Changes the cell height of the list to the value passed as parameter.
• isSelectedIndex(int i) : returns true if the specified index is selected, else false.
• addListSelectionListener(ListSelectionListener l) : adds a listSelectionlistener to the list

68
JList Example
//Example of JList with event handling //adding scroll pane and label to frame
import javax.swing.*; f.add(p);f.add(l);
import javax.swing.event.*; f.setSize(400, 500);
public class JListDemo implements ListSelectionListener{ f.setVisible(true);
JFrame f = new JFrame("JList Demo"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JList<String> jlst; }
JLabel l; //handling list selection event
JScrollPane p; public void valueChanged(ListSelectionEvent lse){
String Cities[]={"Kathmandu","Pokhara","Hetauda","Birgunj", int idx = jlst.getSelectedIndex();
"Dharan","Biratnagar", "Butwal","Dhangadhi","Nepalgunj",
"Damak","Dharan","Bharatpur","Janakpur","Itahari"}; if(idx!=-1)
void makeGUI(){ l.setText("Current City : "+Cities[idx]);
jlst = new JList<String>(Cities); //setting the list selection mode else
jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); l.setText("Choose a city");
//adding the list to scroll pane }
p = new JScrollPane(jlst); //setting size of scroll pane
p.setSize(150, 200); public static void main(String[] args) {
//making label that displays the selection JListDemo jd = new JListDemo();
l = new JLabel("Choose a city"); jd.makeGUI();
//adding selection listener for the list }
jlst.addListSelectionListener(this); }
69
Output

70
JPanel
• JPanel is a Swing’s lightweight container which is used to group a set
of components together.
• It provides space in which an application can attach any other
component.
• JPanel can be added to JFrame.
• JPanel is a Container also: JButton, JLabel, and JPanel can be added to
it.
• The JPanel class resides in the package javax.swing.
➢ JPanel newpanel=new JPanel(); // creates JPanel
➢ container.add(newpanel) // adds the panel to container

71
JPanel : Some methods
• newPanel.setBackground(Color.CYAN); //sets background color
• newPanel.setBorder(BorderFactory.createLineBorder(Color.RED)); // sets line border
• newPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Login Panel")); // set titled and etched border

Example:

72
Dialog Boxes
• Dialog boxes are primarily used to obtain user input and are often child windows of a top-level
window.
• Dialog boxes don’t have menu bars, but in other respects, they function like frame windows. (You
can add controls to them, for example, in the same way that you add controls to a frame window.)
• Dialog boxes may be modal or modeless. When a modal dialog box is active, all input is directed
to it until it is closed. This means that you cannot access other parts of your program until you
have closed the dialog box. When a modeless dialog box is active, input focus can be directed to
another window in your program. Thus, other parts of your program remain active and accessible.
• Two commonly used constructors are shown here:
Dialog(Frame parentWindow, boolean mode)
Dialog(Frame parentWindow, String title, boolean mode)
Here, parentWindow is the owner of the dialog box. If mode is true, the dialog box is modal. Otherwise, it
is modeless. The title of the dialog box can be passed in title.

73
FileDialog
• Java provides a built-in dialog box that lets the user specify a file. To create a file dialog box,
instantiate an object of type FileDialog. This causes a file dialog box to be displayed. Usually, this is
the standard file dialog box provided by the operating system. Here are three FileDialog constructors:
FileDialog(Frame parent)
FileDialog(Frame parent, String boxName)
FileDialog(Frame parent, String boxName, int how)

Here, parent is the owner of the dialog box. The boxName parameter specifies the name displayed in
the box’s title bar.
If boxName is omitted, the title of the dialog box is empty. If how is FileDialog.LOAD, then the box is
selecting a file for reading.
If how is FileDialog.SAVE, the box is selecting a file for writing.
If how is omitted, the box is selecting a file for reading.

74
Javax.swing.JOptionPane

• Java’s JOptionPane class (package javax.swing) provides


prebuilt dialog boxes for both input and output.
• Message dialog box: This is a simple information dialog box and
we call one of the showMessageDialog() methods to create.
• Input dialog box: This is a dialog box that allows a user to type in
some input and call one of the showInputDialog() methods to
create.
• Confirm dialog box: This is a dialog box that presents the user with
a Yes/No/Cancel option and call one of
the showConfirmDialog() methods to create it.
75
Message dialogs
• There are three versions of showMessageDialog()
• void showMessageDialog(Component parentComponent, Object message)
• void showMessageDialog(Component parentComponent, Object message, String title, int messageType)
• void showMessageDialog(Component parentComponent, Object message, String title, int messageType,
Icon icon)
• The parameters:
1. parentComponent: indicates what component this dialog will pop up over. Use null to make the
message not connected to any other component
2. message: This is the actual message being displayed.
3. title: The string that will appear in the pop-up window's title bar
4. messageType: Use one of these static constants from the class. Except for plain message, each one
uses a special icon on the message box
• PLAIN_MESSAGE
• ERROR_MESSAGE
• INFORMATION_MESSAGE
• WARNING_MESSAGE
• QUESTION_MESSAGE
5. icon: A custom icon to use
76
JOptionPane Message Dialog Constants

• The constants that represent the message dialog types are shown in figure below.
• All message dialog types except PLAIN_MESSAGE display an icon to the left of the message.
• These icons provide a visual indication of the message’s importance to the user.
• A QUESTION_MESSAGE icon is the default icon for an input dialog box

77
Message Dialogs
import javax.swing.JOptionPane; JOptionPane.showMessageDialog(null, s2, "Just so you'll
know", JOptionPane.INFORMATION_MESSAGE);
public class MessageDialogDemo {
JOptionPane.showMessageDialog(null, s3, "Oops!",
public static void main(String[] args) {
JOptionPane.ERROR_MESSAGE);
String s1 = "Here are some message boxes for
JOptionPane.showMessageDialog(null, s4, "Danger, Will
your\n" + "edification, education, and Robinson", JOptionPane.WARNING_MESSAGE);
enjoyment\n";
JOptionPane.showMessageDialog(null, s5, "Just curious...",
JOptionPane.showMessageDialog(null, s1); JOptionPane.QUESTION_MESSAGE);
String all = s2 + '\n' + s3 + '\n' + s4 + '\n' + s5;
String s2 = "Dragons have very sharp teeth."; JOptionPane.showMessageDialog(null, all, "And once
more", JOptionPane.PLAIN_MESSAGE);
String s3 = "A dragon ate my grandma by mistake...";
String s4 = "Look out! The dragon is behind you!!!";
}
String s5 = "Are you missing a leg?\n"
}
+ "or did you only have one to begin with?";
78
Using input dialogs
• To get an input box that the user can type into, we can use
the showInputDialog method of JOptionPane.
• Example:
String s1;
s1 = JOptionPane.showInputDialog("Please enter an integer:");
• Note that in the above call, we captured the return value into a variable.
The showInputDialog call will always return the entered value
• Also note that this value always comes back as a String
• If you want to save the entered data as a different type, you will need to
convert it. For example:
int value = Integer.parseInt(s1); // converts s1 into an integer
79
Example:
Program below presents a simple addition application that uses two input dialogs to
obtain integers from the user and a message dialog to display the sum of the integers
the user enters.

import javax.swing.JOptionPane; int number1 = Integer.parseInt( firstNumber );


public class Addition { int number2 = Integer.parseInt( secondNumber );
public static void main( String[] args ) { int sum = number1 + number2;
JOptionPane.showMessageDialog( null, "The sum is
String firstNumber = JOptionPane.showInputDialog ( " + sum, "Sum of Two Integers",
"Enter first integer" ); JOptionPane.PLAIN_MESSAGE );
String secondNumber = }
JOptionPane.showInputDialog ( "Enter second
integer" ); }

80
Confirm Dialogs
• There are several versions of: showConfirmDialog().
• Most of these have very similar options as the showMessageDialog
methods
• Parameters: All calls use the first two. Others are optional
• parentComponent: Same as for message dialogs
• message: Same as for message dialogs
• title: Same as for message dialogs
• optionType: Can be one of these static class constants:
YES_NO_OPTION
YES_NO_CANCEL_OPTION
OK_CANCEL_OPTION
• messageType: Same as for message dialog
• icon: Same as for message dialog

81
Confirm Dialogs
• These methods each return an integer value.
• That value can be captured, and then compared against one of the
following static constants, to determine which one was selected:
YES_OPTION
NO_OPTION
CANCEL_OPTION
OK_OPTION

82
Example: Confirm Dialog
import javax.swing.JOptionPane; if (b == JOptionPane.YES_OPTION)

public class ConfirmDialogDemo { message = "Okay, you will get chocolate ice cream";
public static void main(String[] args) { else if (b == JOptionPane.NO_OPTION)
int a, b, c; message = "Okay, you will get vanilla ice cream";
String message; else
message = "Well, if you're not going to answer the
a = JOptionPane.showConfirmDialog(null, "Would you like some ice question," + "\nI guess you don't get any ice cream!";
cream?", "Question 1", JOptionPane.YES_NO_OPTION); }

if (a == JOptionPane.NO_OPTION) JOptionPane.showMessageDialog(null, message);


message = "Good. More ice cream for me!"; }
else }
{
b = JOptionPane.showConfirmDialog(null, "How about
chocolate?","Question 2", JOptionPane.YES_NO_CANCEL_OPTION);

83
Using Menu with Frames
• Menus are an integral part of GUIs. They allow the user to perform actions
without unnecessarily cluttering a GUI with extra components.
• The classes used to declare menus are JMenuBar, JMenu, JMenuItem,
JCheckBoxMenuItem and class JRadioButtonMenuItem.
• Class JMenuBar contains the methods necessary to manage a menu bar, which is
a container for menus.
• Class JMenu contains the methods necessary for managing menus. Menus
contain menu items and are added to menu bars or to other menus as
submenus. When a menu is clicked, it expands to show its list of menu items.
• Class JMenuItem contains the methods necessary to manage menu items. A
menu item is a GUI component inside a menu that, when selected, causes an
action event. A menu item can be used to initiate an action, or it can be a
submenu that provides more menu items from which the user can select.
Submenus are useful for grouping related menu items in a menu.

84
Using Menu with Frames
• Class JCheckBoxMenuItem (a subclass of javax.swing.JMenuItem) contains the
methods necessary to manage menu items that can be toggled on or off. When a
JCheck-BoxMenuItem is selected, a check appears to the left of the menu item.
When the JCheck-BoxMenuItem is selected again, the check is removed.
• Class JRadioButtonMenuItem (a subclass of javax.swing.JMenuItem) contains the
methods necessary to manage menu items that can be toggled on or off like
JCheckBox-MenuItems. When multiple JRadioButtonMenuItems are maintained
as part of a Button-Group, only one item in the group can be selected at a given
time. When a JRadioButtonMenuItem is selected, a filled circle appears to the left
of the menu item. When another JRadioButtonMenuItem is selected, the filled
circle of the previously selected menu item is removed.

85
Using Menu with Frames
• JMenuBar menubar = new JMenuBar();
• JMenu file = new JMenu("File");
menubar.add(file);
• JMenuItem new_item = new JMenuItem("New");
file.add(new_item);
• JCheckBoxMenuItem item1 = new JCheckBoxMenuItem("item1");
file.add(item1);

86
Example: Menu
JMenuItem close_c = new JMenuItem("Close_Current_Item");
import java.awt.*; close.add(close_c);
import javax.swing.*; JMenuItem close_all = new JMenuItem("Close_All");
import java.awt.event.*; close.add(close_all);

class MenuDemo { JMenu edit = new JMenu("Edit");


static Container c; bar.add(edit);
public static void main(String [] args) { JMenu insert = new JMenu("Insert");
JFrame fr = new JFrame(); bar.add(insert);
fr.setBounds(0,0,500,500);
fr.setVisible(true); JRadioButtonMenuItem lnrsearch = new
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JRadioButtonMenuItem("Linear_Search");
c = fr.getContentPane(); edit.add(lnrsearch);
c.setLayout(new FlowLayout(FlowLayout.LEFT)); JRadioButtonMenuItem bsearch = new
JRadioButtonMenuItem("Binary_Search");
JMenuBar bar = new JMenuBar(); edit.add(bsearch);
c.add(bar); ButtonGroup btngrp = new ButtonGroup();
JMenu file = new JMenu("File"); btngrp.add(lnrsearch);
bar.add(file); btngrp.add(bsearch);
JMenuItem new_item = new JMenuItem("New"); JCheckBoxMenuItem ruler = new JCheckBoxMenuItem("Ruler");
file.add(new_item); insert.add(ruler);
JMenuItem open = new JMenuItem("Open"); JCheckBoxMenuItem thumnail = new
file.add(open); JCheckBoxMenuItem("Thumnail");
JMenuItem save = new JMenuItem("Save"); insert.add(thumnail);
JMenu help = new JMenu("Help");
file.add(save); bar.add(help);
JMenu close = new JMenu("Close");
file.add(close); } }
87
Output

88
JTable
• A table is a component that displays rows and columns of data.
• You can drag the cursor on column boundaries to resize columns. You can also drag a column to a
new position.
• The JTable class is used to display data in tabular form. It is composed of rows and columns.
• Tables are implemented by the JTable class, which extends JComponent.
• One of its constructors is shown here:
JTable(Object data[ ][ ], Object colHeads[ ])
Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-
dimensional array with the column headings.
• Here are the steps for using a table in a Frame:
1. Create a JTable object.
2. Create a JScrollPane object. (The arguments to the constructor specify the table and the
policies for vertical and horizontal scroll bars.)
3. Add the table to the scroll pane.
4. Add the scroll pane to JFrame
89
JTable Example
// Create the table
//TableFrame.java
JTable table = new JTable(data, colHeads);
import javax.swing.JFrame;
// Add table to a scroll pane
import javax.swing.JScrollPane;
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
import javax.swing.JTable;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
import java.awt.BorderLayout;
JScrollPane scrollPane = new JScrollPane(table, v, h);
import javax.swing.*;
// Add scroll pane to Frame
class TableFrame extends JFrame {
this.add(scrollPane, BorderLayout.CENTER);
public TableFrame()
}}
{
this.setLayout(new BorderLayout());
public class TableDemo {
// Initialize column headings
public static void main( String[] args ) {
final String[] colHeads = { "Name", "Phone", "Fax" };
TableFrame tableFrame = new TableFrame();
// Initialize data
tableFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
final String[][] data = { { "Ram", "4567", "8675" }, { "Kiran",
tableFrame.setSize( 250, 200 ); // set frame size
"4567", "8675" },{ "Pashang", "4567", "8675" },{ "Uma",
tableFrame.setVisible( true ); // display frame
"4567", "8675" } };
} // end main
} // end class Table
90
Output

91
MVC Design Patterns
• The Model/View/Controller architecture was introduced as part of
Smalltalk, a popular object-oriented programming language invented by
Alan Kay.
• MVC was designed to reduce the programming effort required to build
systems making use of multiple, synchronized presentations of the
same data.
• Its central characteristics are that the model, the controllers, and the
views are treated as separate entities, and that changes made to the
model should be reflected automatically in each of the views.

92
Benefits of MVC
• The Model/View/Controller architecture has several benefits:
• There is a clearly defined separation between components of a program --
problems in each domain can be solved independently.
• There is a well defined API -- anything that uses the API properly can replace
either the model, the view, or the controller.
• The binding between the model and the view is dynamic -- it occurs at run
time, rather than at compile time.
• By incorporating the MVC architecture into a design, pieces of a
program can be designed separately (and designed to do their job
well) and then bound together at run time.
• If a component is later deemed to be unsuitable, it can be replaced
without affecting the other pieces.
93
Model
• The model is the object that represents the data in the program.
• It manages the data and conducts all transformations on that data.
• The model has no specific knowledge of either its controllers or its
views -- it contains no internal references to either.
• Rather, the system itself takes on the responsibility of maintaining
links between the model and its views and notifying the views when
the model changes.

94
View
• The view is the object that manages the visual display of the data
represented by the model.
• It produces the visual representation of the model object and displays
the data to the user.
• It interacts with the model via a reference to the model object itself.

95
Controller
• The controller is the object that provides the means for user
interaction with the data represented by the model.
• It provides the means by which changes are made, either to the
information in the model or to the appearance of the view.
• It interacts with the model via a reference to the model object itself.

96
Adapter Classes
• Java provides a special feature, called an adapter class, that can simplify the
creation of event handlers in certain situations.
• An adapter class provides an empty implementation of all methods in an event
listener interface.
• Adapter classes are useful when you want to receive and process only some of the
events that are handled by a particular event listener interface.
• You can define a new class to act as an event listener by extending one of the
adapter classes and implementing only those events in which you are interested.
• Adapters are replacement to listeners. The advantage with adapter is we can
override any number of methods we would like and not all.
• For example, if we use WindowAdapter (instead of WindowListener), we can
override only one method to close the frame.

97
What is the problem with listener interfaces?

• Actually problem does not occur with every listener, but occurs with a
few. A few listeners contain more than one abstract method.
• For example, WindowListener, used for frame closing, comes with 7
abstract methods. We are interested in only one abstract method to
close the frame, but being WindowListener is an interface, we are
forced to override remaining 6 methods also, just at least with empty
body. This is the only problem, else fine.
• Some listeners like ActionListener comes with only one abstract
method and with them no problem at all.

98
java.awt.event Adapter classes

Adapter class Listener interface


WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
99
MouseMotionAdapter Example
f.setLayout (null);
// importing the necessary libraries f.setVisible (true);
import javax.swing.*; }
import java.awt.*; // overriding the mouseDragged() method
import java.awt.event.*; public void mouseDragged (MouseEvent e) {
// class which inherits the MouseMotionAdapter class // creating the Graphics object and fetching them from the
public class MouseMotionAdapterDemo extends //Frame object using getGraphics() method
MouseMotionAdapter { Graphics g = f.getGraphics();
JFrame f; // setting the color of graphics object
// class constructor g.setColor (Color.ORANGE);
MouseMotionAdapterDemo() { // setting the shape of graphics object
// creating the frame with the title g.fillOval (e.getX(), e.getY(), 20, 20);
f = new JFrame ("Mouse Motion Adapter"); }
// adding MouseMotionListener to the Frame public static void main(String[] args) {
f.addMouseMotionListener (this); new MouseMotionAdapterDemo();
// setting the size, layout and visibility of the frame }
f.setSize (300, 300); }

100
Output

101
Thank you !

102

You might also like