0% found this document useful (0 votes)
24 views21 pages

Awt MVC

mvc architechture and AWT NOTES

Uploaded by

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

Awt MVC

mvc architechture and AWT NOTES

Uploaded by

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

Java AWT Tutorial

Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or
windows-based applications in Java.

Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavy weight i.e. its components are using the resources of
underlying operating system (OS).

The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

The AWT tutorial will help the user to understand Java GUI programming in simple and easy
steps.

Backward Skip 10sPlay VideoForward Skip 10s

ADVERTISEMENT

Why AWT is platform independent?

Java AWT calls the native platform calls the native platform (operating systems) subroutine for
creating API components like TextField, ChechBox, button, etc.

For example, an AWT GUI with components like TextField, label and button will have different
look and feel for the different platforms like Windows, MAC OS, and Unix. The reason for this
is the platforms have different view for their native components and AWT directly calls the
native subroutine that creates those components.

In simple words, an AWT application will look like a windows application in Windows OS
whereas it will look like a Mac application in the MAC OS.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.


Components

All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT,
there are classes for each component as shown in above diagram. In order to place every
component in a particular position on a screen, we need to add them to a container.

Container

The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such
as Frame, Dialog and Panel.

ADVERTISEMENT
ADVERTISEMENT

It is basically a screen where the where the components are placed at their specific locations.
Thus it contains and controls the layout of components.
Note: A container itself is a component (see the above diagram), therefore we can add a
container inside container.

Types of containers:

There are four types of containers in Java AWT:

1. Window
2. Panel
3. Frame
4. Dialog

Window

The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window. We need to create an instance of Window class to create
this container.

Panel

The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components.

Frame

The Frame is the container that contain title bar and border and can have menu bars. It can have
other components like button, text field, scrollbar etc. Frame is most widely used container while
developing an AWT application.

Useful Methods of Component Class

Method Description
public void add(Component c) Inserts a component on
this component.
public void setSize(int Sets the size (width and
width,int height) height) of the component.
public void Defines the layout
setLayout(LayoutManager m) manager for the
component.
public void setVisible(boolean Changes the visibility of
status) the component, by
default false.
Java AWT Example

To create simple AWT example, you need a frame. There are two ways to create a GUI using
Frame in AWT.

ADVERTISEMENT
ADVERTISEMENT
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)

ADVERTISEMENT

AWT Example by Inheritance

Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing
Button component on the Frame.

AWTExample1.java

1. // importing Java AWT class


2. import java.awt.*;
3.
4. // extending Frame class to our class AWTExample1
5. public class AWTExample1 extends Frame {
6.
7. // initializing using constructor
8. AWTExample1() {
9.
10. // creating a button
11. Button b = new Button("Click Me!!");
12.
13. // setting button position on screen
14. b.setBounds(30,100,80,30);
15.
16. // adding button into frame
17. add(b);
18.
19. // frame size 300 width and 300 height
20. setSize(300,300);
21.
22. // setting the title of Frame
23. setTitle("This is our basic AWT example");
24.
25. // no layout manager
26. setLayout(null);
27.
28. // now frame will be visible, by default it is not visible
29. setVisible(true);
30. }
31.
32. // main method
33. public static void main(String args[]) {
34.
35. // creating instance of Frame class
36. AWTExample1 f = new AWTExample1();
37.
38. }
39.
40. }
download this example

The setBounds(int x-axis, int y-axis, int width, int height) method is used in the above example
that sets the position of the awt button.

ADVERTISEMENT

Output:

AWT Example by Association

Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are
creating a TextField, Label and Button component on the Frame.

ADVERTISEMENT
ADVERTISEMENT

AWTExample2.java

1. // importing Java AWT class


2. import java.awt.*;
3.
4. // class AWTExample2 directly creates instance of Frame class
5. class AWTExample2 {
6.
7. // initializing using constructor
8. AWTExample2() {
9.
10. // creating a Frame
11. Frame f = new Frame();
12.
13. // creating a Label
14. Label l = new Label("Employee id:");
15.
16. // creating a Button
17. Button b = new Button("Submit");
18.
19. // creating a TextField
20. TextField t = new TextField();
21.
22. // setting position of above components in the frame
23. l.setBounds(20, 80, 80, 30);
24. t.setBounds(20, 100, 80, 30);
25. b.setBounds(100, 100, 80, 30);
26.
27. // adding components into frame
28. f.add(b);
29. f.add(l);
30. f.add(t);
31.
32. // frame size 300 width and 300 height
33. f.setSize(400,300);
34.
35. // setting the title of frame
36. f.setTitle("Employee info");
37.
38. // no layout
39. f.setLayout(null);
40.
41. // setting visibility of frame
42. f.setVisible(true);
43. }
44.
45. // main method
46. public static void main(String args[]) {
47.
48. // creating instance of Frame class
49. AWTExample2 awt_obj = new AWTExample2();
50.
51. }
52.
53. }
download this example

Output:

MVC Design Pattern


Last Updated : 19 Feb, 2024



The MVC design pattern is a software architecture pattern that separates an application into three
main components: Model, View, and Controller, making it easier to manage and maintain the
codebase. It also allows for the reusability of components and promotes a more modular
approach to software development.
Important Topics for the MVC Design Pattern
 What is the MVC Design Pattern?
 Components of the MVC Design Pattern
 Communication between the components
 Example of the MVC Design Pattern
 Advantages of the MVC Design Pattern
 Disadvantages of the MVC Design Pattern
What is the MVC Design Pattern?
The Model View Controller (MVC) design pattern specifies that an application consists of a
data model, presentation information, and control information. The pattern requires that each of
these be separated into different objects.
 The MVC pattern separates the concerns of an application into three distinct components, each
responsible for a specific aspect of the application’s functionality.
 This separation of concerns makes the application easier to maintain and extend, as changes to
one component do not require changes to the other components.
Components of the MVC Design Pattern
1. Model
The Model component in the MVC (Model-View-Controller) design pattern represents the data
and business logic of an application. It is responsible for managing the application’s data,
processing business rules, and responding to requests for information from other components,
such as the View and the Controller.
2. View
Displays the data from the Model to the user and sends user inputs to the Controller. It is passive
and does not directly interact with the Model. Instead, it receives data from the Model and sends
user inputs to the Controller for processing.
3. Controller
Controller acts as an intermediary between the Model and the View. It handles user input and
updates the Model accordingly and updates the View to reflect changes in the Model. It contains
application logic, such as input validation and data transformation.
Communication between the components
This below communication flow ensures that each component is responsible for a specific aspect
of the application’s functionality, leading to a more maintainable and scalable architecture
 User Interaction with View:
o The user interacts with the View, such as clicking a button or entering text into a
form.
 View Receives User Input:
o The View receives the user input and forwards it to the Controller.
 Controller Processes User Input:
o The Controller receives the user input from the View.
o It interprets the input, performs any necessary operations (such as updating the
Model), and decides how to respond.
 Controller Updates Model:
o The Controller updates the Model based on the user input or application logic.
 Model Notifies View of Changes:
o If the Model changes, it notifies the View.
 View Requests Data from Model:
o The View requests data from the Model to update its display.
 Controller Updates View:
o The Controller updates the View based on the changes in the Model or in response to
user input.
 View Renders Updated UI:
o The View renders the updated UI based on the changes made by the Controller.
Example of the MVC Design Pattern
Below is the code of above problem statement using MVC Design Pattern:
Let’s break down into the component wise code:
1. Model (Student class)
Represents the data (student’s name and roll number) and provides methods to access and
modify this data.
 Java

class Student {

private String rollNo;


private String name;

public String getRollNo() {

return rollNo;

public void setRollNo(String rollNo) {

this.rollNo = rollNo;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

2. View (StudentView class)


Represents how the data (student details) should be displayed to the user. Contains a method
(printStudentDetails) to print the student’s name and roll number.
 Java

class StudentView {

public void printStudentDetails(String


studentName, String studentRollNo) {

System.out.println("Student:");
System.out.println("Name: " +
studentName);

System.out.println("Roll No: " +


studentRollNo);

3. Controller (StudentController class)


Acts as an intermediary between the Model and the View. Contains references to the Model and
View objects. Provides methods to update the Model
(e.g., setStudentName, setStudentRollNo) and to update the View (updateView).
 Java

class StudentController {

private Student model;

private StudentView view;

public StudentController(Student model, StudentView view) {

this.model = model;

this.view = view;

public void setStudentName(String name) {

model.setName(name);

public String getStudentName() {

return model.getName();

}
public void setStudentRollNo(String rollNo) {

model.setRollNo(rollNo);

public String getStudentRollNo() {

return model.getRollNo();

public void updateView() {

view.printStudentDetails(model.getName(), model.getRollNo());

Complete code for the above example


Below is the complete code for the above example:
 Java

class Student {

private String rollNo;

private String name;

public String getRollNo() {

return rollNo;

public void setRollNo(String rollNo) {


this.rollNo = rollNo;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

class StudentView {

public void printStudentDetails(String studentName, String studentRollNo) {

System.out.println("Student:");

System.out.println("Name: " + studentName);

System.out.println("Roll No: " + studentRollNo);

class StudentController {

private Student model;

private StudentView view;

public StudentController(Student model, StudentView view) {


this.model = model;

this.view = view;

public void setStudentName(String name) {

model.setName(name);

public String getStudentName() {

return model.getName();

public void setStudentRollNo(String rollNo) {

model.setRollNo(rollNo);

public String getStudentRollNo() {

return model.getRollNo();

public void updateView() {

view.printStudentDetails(model.getName(), model.getRollNo());

}
public class MVCPattern {

public static void main(String[] args) {

Student model = retriveStudentFromDatabase();

StudentView view = new StudentView();

StudentController controller = new StudentController(model, view);

controller.updateView();

controller.setStudentName("Vikram Sharma");

controller.updateView();

private static Student retriveStudentFromDatabase() {

Student student = new Student();

student.setName("Lokesh Sharma");

student.setRollNo("15UCS157");

return student;

 Output

Student:
Name: Lokesh Sharma

Roll No: 15UCS157

Student:

Name: Vikram Sharma

Roll No: 15UCS157

Advantages of the MVC Design Pattern


 Separation of Concerns: MVC separates the different aspects of an application (data, UI, and
logic), making the code easier to understand, maintain, and modify.
 Modularity: Each component (Model, View, Controller) can be developed and tested
separately, promoting code reusability and scalability.
 Flexibility: Since the components are independent, changes to one component do not affect
the others, allowing for easier updates and modifications.
 Parallel Development: Multiple developers can work on different components
simultaneously, speeding up the development process.
 Code Reusability: The components can be reused in other parts of the application or in
different projects, reducing development time and effort.
Disadvantages of the MVC Design Pattern
 Complexity: Implementing the MVC pattern can add complexity to the code, especially for
simpler applications, leading to overhead in development.
 Learning Curve: Developers need to understand the concept of MVC and how to implement
it effectively, which may require additional time and resources.
 Overhead: The communication between components (Model, View, Controller) can lead to
overhead, affecting the performance of the application, especially in resource-constrained
environments.
 Potential for Over-Engineering: In some cases, developers may over-engineer the
application by adding unnecessary abstractions and layers, leading to bloated and hard-to-
maintain code.
 Increased File Count: MVC can result in a larger number of files and classes compared to
simpler architectures, which may make the project structure more complex and harder to
navigate.
 GridBagLayout gbl=new GridBagLayout();
 setLayout(gbl);
 GridBagConstraints gbc=new GridBagConstraints();
 gbc.insets = new Insets(10, 10, 10, 10);

 JLabel jl = new JLabel("This is a JLabel!", SwingConstants.CENTER);
 jl.setBorder(BorderFactory.createLineBorder(Color.black));
 gbc.gridy = 0;
 gbc.gridx = 0;
 gbc.ipadx = 50;
 gbc.ipady = 50;
 add(jl, gbc);

 gbc.insets = new Insets(10, 10, 10, 10);
 JLabel jl2 = new JLabel("This is a JLabel!", SwingConstants.CENTER);
 jl2.setBorder(BorderFactory.createLineBorder(Color.black));
 gbc.gridy = 1;
 gbc.gridx = 1;
 gbc.ipadx = 50;
 gbc.ipady = 50;
 add(jl2, gbc);
 Use the gridy and gridx attributes to specify the position of the JLabels in the
GridBagLayout-Table.

How to Use GridBagLayout: Specifying Constraints


Below is some of the code you'll typically see in a container that uses
a GridBagLayout . (You'll see an fleshed out example on the next page.)
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(gridbag);

//For each component to be added to this container:


//...Create the component...
//...Set instance variables in the GridBagConstraints instance...
gridbag.setConstraints(theComponent, c);
add(theComponent);
As you might have guessed from the above example, you can reuse the same
GridBagConstraints instance for multiple components, even if the components have
different constraints. The GridBagLayout extracts the constraint values and doesn't
use the GridBagConstraints again. You must be careful, however, to reset the
GridBagConstraints instance variables to their default values when necessary.

You can set the following GridBagConstraints instance variables:

gridx, gridy

Specify the row and column at the upper left of the component. The leftmost
column has address gridx=0, and the top row has address gridy=0.
Use GridBagConstraints.RELATIVE (the default value) to specify that the
component be placed just to the right of (for gridx) or just below (for gridy)
the component that was added to the container just before this component
was added.
gridwidth, gridheight

Specify the number of columns (for gridwidth) or rows (for gridheight) in the
component's display area. These constraints specify the number of cells the
component uses, not the number of pixels it uses. The default value is 1.
Use GridBagConstraints.REMAINDER to specify that the component be the last
one in its row (for gridwidth) or column (for gridheight).
Use GridBagConstraints.RELATIVE to specify that the component be the next
to last one in its row (for gridwidth) or column (for gridheight).

Note: Due to a bug in the the 1.0 release of Java, GridBagLayout doesn't allow
components to span multiple rows unless the component is in the leftmost
column.
fill

Used when the component's display area is larger than the component's
requested size to determine whether and how to resize the component. Valid
values are GridBagConstraints.NONE (the
default), GridBagConstraints.HORIZONTAL (make the component wide enough
to fill its display area horizontally, but don't change its
height), GridBagConstraints.VERTICAL (make the component tall enough to fill
its display area vertically, but don't change its width),
and GridBagConstraints.BOTH (make the component fill its display area
entirely).

ipadx, ipady

Specifies the internal padding: how much to add to the minimum size of the
component. The default value is zero. The width of the component will be at
least its minimum width plus ipadx*2 pixels (since the padding applies to both
sides of the component). Similarly, the height of the component will be at
least its minimum height plus ipady*2 pixels.
insets

Specifies the external padding of the component -- the minimum amount of


space between the component and the edges of its display area. The value is
specified as an Insets object. By default, each component has no external
padding.
anchor

Used when the component is smaller than its display area to determine where
(within the area) to place the component. Valid values
are GridBagConstraints.CENTER (the
default), GridBagConstraints.NORTH, GridBagConstraints.NORTHEAST, GridBagCo
nstraints.EAST, GridBagConstraints.SOUTHEAST, GridBagConstraints.SOUTH, Gr
idBagConstraints.SOUTHWEST, GridBagConstraints.WEST,
and GridBagConstraints.NORTHWEST.

weightx, weighty

Specifying weights is an art that can have a significant impact on the


appearance of the components a GridBagLayout controls. Weights are used to
determine how to distribute space among columns (weightx) and among rows
(weighty); this is important for specifying resizing behavior.

Unless you specify at least one nonzero value for weightx or weighty, all the
components clump together in the center of their container. This is because
when the weight is 0.0 (the default), the GridBagLayout puts any extra space
between its grid of cells and the edges of the container.

Generally weights are specified with 0.0 and 1.0 as the extremes, with numbers
in between used as necessary. Larger numbers indicate that the component's
row or column should get more space. For each column, the weight is related to
the highest weightx specified for a component within that column (with each
multi-column component's weight being split somehow between the columns
the component is in). Similarly, each row's weight is related to the
highest weighty specified for a component within that row. Extra space tends to
go toward the rightmost column and bottom row.

You might also like