0% found this document useful (0 votes)
11 views48 pages

Attachment (1)

This document provides an overview of Java's Abstract Window Toolkit (AWT) for creating graphical user interfaces (GUIs). It discusses AWT components, containers, and their types, as well as various GUI elements like buttons, text fields, and layout managers. Additionally, it includes a practical example of building a calculator application using AWT components.

Uploaded by

adityapandji1
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)
11 views48 pages

Attachment (1)

This document provides an overview of Java's Abstract Window Toolkit (AWT) for creating graphical user interfaces (GUIs). It discusses AWT components, containers, and their types, as well as various GUI elements like buttons, text fields, and layout managers. Additionally, it includes a practical example of building a calculator application using AWT components.

Uploaded by

adityapandji1
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/ 48

Java Programming

Chapter 4 - K Scheme
Event Handling Using AWT & Swing
Notes

Quote of the day: The expert in anything was once a beginner

Abstract Windowing Toolkit

Definition: 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).

Java मे GUI (Graphical User Interface) create करने के 2 तरीके है , पहला AWT
और दू सरा SWING. Swing AWT का extended version है , इसमे कुछ advanced
features होते है । AWT के दारा भी अची graphical application develop की जा
सकती है । AWT एक GUI library होती है , जो graphical application मे graphical
components(Buttons, Text box, Check box) add करने के ललए packages और
classes provide करती है । AWT library को लकसी भी java program के साथ यूज
लकया जा सकता है । उसके ललए आपको java.awt.* package को import करना पडता
है ।

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Features of AWT in Java
 AWT is a set of native user interface components
 It is based upon a robust event-handling model
 It provides Graphics and imaging tools, such as shape, color, and font
classes
 AWT also avails layout managers which helps in increasing the flexibility
of the window layouts
 Data transfer classes are also a part of AWT that helps in cut-and-paste
through the native platform clipboard
 Supports a wide range of libraries that are necessary for creating graphics
for gaming products, banking services, educational purposes, etc.

Container in Java :

Containers are integral part of AWT GUI components. A container provides a


space where a component can be located. A Container in AWT is a component
itself and it adds the capability to add component to itself. Following are
noticable points to be considered.

 Sub classes of Container are called as Containter. For example Panel,


Frame and Window.
 Container can add only Component to itself.
 A default layout is present in each container which can be overridden
using setLayout method.

Types of containers:

There are four types of containers in Java AWT:

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


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.

In hindi:

Classes Explanation

Window ये एक window होती है । इस window की border नहीं होती है ।

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


और इसमे menu bar भी नहीं होता है ।

ये एक window होती है । इसमे title bar और menu bar नहीं


Panel
होते है । और इस window की border भी नहीं होती है ।

ये एक window होती है । इसमे menu bar और title bar होते है ।


Frame
और इस window की borders भी होती है ।

ये लकसी दू सरी window के अंदर एक window होती है । ये


Dialog लकसी user event पर कोई message और उसके साथ action
लेने के ललए components को display करती है ।

AWT Controls

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


AWT Components
1. Containers

Container in Java AWT is a component that is used to hold other components


such as text fields, buttons, etc. It is a subclass of java.awt.Component and is
responsible for keeping a track of components being added. There are four types
of containers provided by AWT in Java.

Types of Containers

1. Window: It is an instance of the Window class having neither border nor


title. It is used for creating a top-level window.
2. Frame: Frame is a subclass of Window and contains title, border and
menu bars. It comes with a resizing canvas and is the most widely used
container for developing AWT applications. It is capable of holding

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


various components such as buttons, text fields, scrollbars, etc. You can
create a Java AWT Frame in two ways:
i. By Instantiating Frame class
ii. By extending Frame class
3. Dialog: Dialog class is also a subclass of Window and comes with the
border as well as the title. Dialog class’s instance always needs an
associated Frame class instance to exist.
4. Panel: Panel is the concrete subclass of Container and doesn’t contain
any title bar, menu bar or border. Panel class is a generic container for
holding the GUI components. You need the instance of the Panel class in
order to add the components.

That was all about the container and its types let us now move further in this
Java AWT Tutorial article and learn about the rest of the components.

2. Button

java.awt.Button class is used to create a labeled button. GUI component that


triggers a certain programmed action upon clicking it. The Button class has two
constructors:

//Construct a Button with the given label

public Button(String btnLabel);

//Construct a Button with empty label

public Button();

A few of the methods provided by this class have been listed below:

//Get the label of this Button instance

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


public String getLabel();

//Set the label of this Button instance

public void setLabel(String btnLabel);

//Enable or disable this Button. Disabled Button cannot be clicked

public void setEnable(boolean enable);

3. Text Field

A java.awt.TextField class creates a single-line text box for users to enter texts.
The TextField class has three constructors which are:

//Construct a TextField instance with the given initial text string with the
number of columns.

public TextField(String initialText, int columns);

//Construct a TextField instance with the given initial text string.

public TextField(String initialText);

//Construct a TextField instance with the number of columns.

public TextField(int columns);

A few of the methods provided by TextField class are:

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


// Get the current text on this TextField instance

public String getText();

// Set the display text on this TextField instance

public void setText(String strText);

//Set this TextField to editable (read/write) or non-editable (read-only)

public void setEditable(boolean editable);

4. Label

The java.awt.Label class provides a descriptive text string that is visible on GUI.
An AWT Label object is a component for placing text in a container. Label
class has three constructors which are:

// Construct a Label with the given text String, of the text alignment

public Label(String strLabel, int alignment);

//Construct a Label with the given text String

public Label(String strLabel);

//Construct an initially empty Label

public Label();

This class also provides 3 constants which are:

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


public static final LEFT; // Label.LEFT

public static final RIGHT; // Label.RIGHT

public static final CENTER; // Label.CENTER

Below I have listed down the public methods provided by this class:

public String getText();

public void setText(String strLabel);

public int getAlignment();

//Label.LEFT, Label.RIGHT, Label.CENTER

public void setAlignment(int alignment);

Programming & Frameworks Training

5. Canvas

A Canvas class represents the rectangular area where you can draw in an
application or receive inputs created by the user.

6. Choice

Choice class is used to represent a pop-up menu of choices. The selected choice
is shown on the top of the given menu.

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


7. Scroll Bar

The Scrollbar class object is used to add horizontal and vertical scrollbar in the
GUI. It enables a user to see the invisible number of rows and columns.

8. List

The object of List class represents a list of text items. Using the List class a user
can choose either one item or multiple items.

9. CheckBox

The Checkbox is a class is a graphical component that is used to create a


checkbox. It has two state options; true and false. At any point in time, it can
have either of the two.

So, that was all you need to know about the AWT components. Now, I hope
you are ready to get your feet wet with Java AWT application.

In the next section of this Java AWT tutorial, I will show you how to build a
calculator using AWT components.

Example : Developing a Calculator with Java AWT

Here I will show you how to create a calculator using AWT, where you will be
able to perform basic mathematical operations. Below is a screenshot of how
your Calculator will look like:

Now in order to build this, you need to type in the following code:

package urengineeringfriend.awt;

import java.awt.*;

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class Calculator extends Frame implements


ActionListener

{
Label lb1,lb2,lb3;

TextField txt1,txt2,txt3;

Button btn1,btn2,btn3,btn4,btn5,btn6,btn7;

public Calculator()
{
lb1 = new Label("Var 1");
lb2 = new Label("Var 2");
lb3 = new Label("Result");

txt1 = new TextField(10);


txt2 = new TextField(10);
txt3 = new TextField(10);

btn1 = new Button("Add");


btn2 = new Button("Sub");
btn3 = new Button("Multi");
btn4 = new Button("Div");
btn5 = new Button("Mod");
btn6 = new Button("Reset");
btn7 = new Button("Close");

add(lb1);
add(txt1);
add(lb2);

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


add(txt2);
add(lb3);
add(txt3);
add(btn1);
add(btn2);
add(btn3);
add(btn4);
add(btn5);
add(btn6);
add(btn7);

setSize(200,200);
setTitle("Calculator");
setLayout(new FlowLayout());
//setLayout(new
FlowLayout(FlowLayout.RIGHT));
//setLayout(new
FlowLayout(FlowLayout.LEFT));
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
btn4.addActionListener(this);
btn5.addActionListener(this);
btn6.addActionListener(this);
btn7.addActionListener(this);

}
public void actionPerformed(ActionEvent ae) {
double a=0,b=0,c=0;
try
{
a = Double.parseDouble(txt1.getText());
}
catch (NumberFormatException e) {

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


txt1.setText("Invalid input");
}
try
{
b = Double.parseDouble(txt2.getText());
}
catch (NumberFormatException e) {
txt2.setText("Invalid input");
}
if(ae.getSource()==btn1)
{
c = a + b;
txt3.setText(String.valueOf(c));
}
if(ae.getSource()==btn2)
{
c = a - b;
txt3.setText(String.valueOf(c));
}
if(ae.getSource()==btn3)
{
c = a * b;
txt3.setText(String.valueOf(c));
}
if(ae.getSource()==btn4)
{
c = a / b;
txt3.setText(String.valueOf(c));
}
if(ae.getSource()==btn5)
{
c = a % b;
txt3.setText(String.valueOf(c));

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


}
if(ae.getSource()==btn6)
{
txt1.setText("0");
txt2.setText("0");
txt3.setText("0");
}
if(ae.getSource()==btn7)
{
System.exit(0);
}
}
public static void main(String[] args)
{
Calculator calC = new Calculator();
calC.setVisible(true);
calC.setLocation(300,300);
}
}

As you might have noticed that here we have used just functionalities. You can
always add more functions to your application and create a full-fledged
Calculator.

Layout Manager

The LayoutManagers are used to arrange components in a particular manner.


The Java LayoutManagers facilitates us to control the positioning and size of

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


the components in GUI forms. LayoutManager is an interface that is
implemented by all the classes of layout managers.

The Abstract Windowing Toolkit (AWT) has the following five layout
managers:

 java.awt.BorderLayout
 java.awt.FlowLayout
 java.awt.GridLayout
 java.awt.CardLayout
 java.awt.GridBagLayout

Border Layout Manager

In the Border Layout Manager, the components are positioned in five different
areas (regions). In other words, North, South, East, West and Center. Each
region 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.

Example

1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
4. public class Border extends JFrame
5. implements ActionListener {
6. private JButton b[];
7. private String names[] = {
8. "Hide North Border",
9. "Hide South Border",
10. "Hide East Border",
11. "Hide West Border",
12. "Hide Center Border"
13. };

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


14. private BorderLayout layout;
15. public Border() {
16. super("BorderLayout");
17. layout = new BorderLayout(5, 5);
18. Container c = getContentPane();
19. c.setLayout(layout);
20. b = new JButton[names.length];
21. for (int i = 0; i < names.length; i++) {
22. b[i] = new JButton(names[i]);
23. b[i].addActionListener(this);
24. }
25. c.add(b[0], BorderLayout.NORTH);
26. c.add(b[1], BorderLayout.SOUTH);
27. c.add(b[2], BorderLayout.EAST);
28. c.add(b[3], BorderLayout.WEST);
29. c.add(b[4], BorderLayout.CENTER);
30. setSize(400, 300);
31. show();
32. }
33. public void actionPerformed(ActionEvent e) {
34. for (int i = 0; i < b.length; i++)
35. if (e.getSource() == b[i])
36. b[i].setVisible(false);
37. else
38. b[i].setVisible(true);
39. layout.layoutContainer(getContentPane());
40. }
41. public static void main(String args[]) {
42. Border bord = new Border();
43. bord.addWindowListener(new WindowAdapter() {
44. public void windowClosing(WindowEvent e) {
45. System.exit(0);
46. }
47. });
48. }
49. }

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Grid Layout Manager

Grid Layout is used to place the components in a grid of cells


(rectangular). Each component takes the available space within its cell. Each
cell, has exactly the same size and displays only one component. If the Grid
Layout window is expanded, the Grid Layout changes the cell size, so that the
cells are as large as possible.

In other words, 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. This type of layout is known as, the Grid Layout Manager.

Example

1. import java.awt.*;
2. import java.awt.event.*;

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


3. import javax.swing.*;
4. public class Grid extends JFrame implements ActionListener {
5. private JButton b[];
6. private String names[] = {
7. "Contacts",
8. "Message",
9. "Call Log",
10. "Games",
11. "Settings",
12. "Applications",
13. "Music",
14. "Gallery",
15. "Organiser"
16. };
17. private boolean toggle = true;
18. private Container c;
19. private GridLayout grid1, grid2, grid3;
20. public Grid() {
21. super("GridLayout");
22. grid1 = new GridLayout(2, 3, 5, 5);
23. grid2 = new GridLayout(3, 2);
24. grid3 = new GridLayout(3, 5);
25. c = getContentPane();
26. c.setLayout(grid3);
27. b = new JButton[names.length];
28. for (int i = 0; i < names.length; i++) {
29. b[i] = new JButton(names[i]);
30. b[i].addActionListener(this);
31. c.add(b[i]);
32. }
33. setSize(400, 400);
34. show();
35. }
36. public void actionPerformed(ActionEvent e) {
37. if (toggle)
38. c.setLayout(grid3);
39. else if (toggle)
40. c.setLayout(grid2);
41. else
42. c.setLayout(grid1);
43. toggle = !toggle;
44. c.validate();
45. }
46. public static void main(String args[]) {
47. Grid G = new Grid();
48. G.addWindowListener(new WindowAdapter() {
49. public void windowClosing(WindowEvent e) {
50. System.exit(0);
51. }
52. });

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


53. }
54. }

Output

Flow Layout manager

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).
Example

1. import java.awt.*;
2. import javax.swing.*;
3. public class Flow {

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


4. JFrame f;
5. public Flow() {
6. f = new JFrame();
7. JButton b1 = new JButton("Red");
8. JButton b2 = new JButton("Green");
9. JButton b3 = new JButton("Yellow");
10. JButton b4 = new JButton("Purple");
11. JButton b5 = new JButton("Blue");
12. JButton b6 = new JButton("Pink");
13. JButton b7 = new JButton("Brown");
14. f.add(b1);
15. f.add(b2);
16. f.add(b3);
17. f.add(b4);
18. f.add(b5);
19. f.add(b6);
20. f.add(b7);
21. f.setLayout(new FlowLayout(FlowLayout.LEFT));
22. f.setSize(400, 200);
23. f.setVisible(true);
24. }
25. public static void main(String[] args) {
26. new Flow();
27. }
28. }

Output

Card Layout Manager

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


The card layout class manages two or more components that share the same
display space, in such a way that only one component is visible at a time.

Basically, each card is like a playing card in a stack, in which only the top card
is visible at any time. That is why it is known, as the Card Layout
Manager. Each card is normally a panel that can use any layout manager.

Example

1. import java.awt.*;
2. import javax.swing.*;
3. public class Flow {
4. JFrame f;
5. public Flow() {
6. f = new JFrame();
7. JButton b1 = new JButton("Red");
8. JButton b2 = new JButton("Green");
9. JButton b3 = new JButton("Yellow");
10. JButton b4 = new JButton("Purple");
11. JButton b5 = new JButton("Blue");
12. JButton b6 = new JButton("Pink");
13. JButton b7 = new JButton("Brown");
14. f.add(b1);
15. f.add(b2);
16. f.add(b3);
17. f.add(b4);
18. f.add(b5);
19. f.add(b6);
20. f.add(b7);
21. f.setLayout(new FlowLayout(FlowLayout.LEFT));
22. f.setSize(400, 200);
23. f.setVisible(true);
24. }
25. public static void main(String[] args) {
26. new Flow();
27. }
28. }

Output

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Outputs after clicking "Next card" and "Last card" and then "previous card":

Next card

Last card

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


The previous card will be the next card, in other words, card two.

GridBag Layout Manager

The GridBag layout manages the components in rows or columns that allow
specified components to span multiple rows and columns. Not all the rows and
columns have the same height and width.

This is the most complex layout manager, since it specifies the size and position
characteristics of its components, by specifying constraints for each component.

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Example

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class GridBag extends JFrame {
5. private Container container;
6. private GridBagLayout gbLayout;
7. private GridBagConstraints gbConstraints;
8. public GridBag() {
9. super("GridBagLayout manager");
10. container = getContentPane();
11. gbLayout = new GridBagLayout();
12. container.setLayout(gbLayout);
13. gbConstraints = new GridBagConstraints();
14. JTextArea ta = new JTextArea("TextField1", 5, 10);
15. JTextArea tx = new JTextArea("TextField2", 2, 2);
16. String names[] = {
17. "Laptop",
18. "Palmtop",
19. "Tablet",
20. "Mobile"
21. };
22. JComboBox cb = new JComboBox(names);
23. JTextField tf = new JTextField("TextField");
24. JButton b1 = new JButton("Button 1");
25. JButton b2 = new JButton("Button 2");
26. JButton b3 = new JButton("Button 3");
27. gbConstraints.fill = GridBagConstraints.BOTH;
28. addComponent(ta, 0, 0, 1, 3);
29. gbConstraints.fill = GridBagConstraints.HORIZONTAL;
30. addComponent(b1, 0, 1, 2, 1);
31. addComponent(cb, 2, 1, 2, 1);
32. gbConstraints.weightx = 1000;
33. gbConstraints.weighty = 1;
34. gbConstraints.fill = GridBagConstraints.BOTH;
35. addComponent(b2, 1, 1, 1, 1);
36. gbConstraints.weightx = 0;
37. gbConstraints.weighty = 0;
38. addComponent(b3, 1, 2, 1, 1);
39. addComponent(tf, 3, 0, 2, 1);
40. addComponent(tx, 3, 2, 1, 1);
41. setSize(350, 200);
42. show();
43. }
44. private void addComponent(Component c, int row, int column, int width, int height)
{
45. gbConstraints.gridx = column;

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


46. gbConstraints.gridy = row;
47. gbConstraints.gridwidth = width;
48. gbConstraints.gridheight = height;
49. gbLayout.setConstraints(c, gbConstraints);
50. container.add(c);
51. }
52. public static void main(String args[]) {
53. GridBag app = new GridBag();
54. app.addWindowListener(new WindowAdapter() {
55. public void windowClosing(WindowEvent e) {
56. System.exit(0);
57. }
58. });
59. }
60. }

Output

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Menu & Menu Bar

The object of MenuItem class adds a simple labeled menu item on menu. The
items used in a menu must belong to the MenuItem or any of its subclass.

The object of Menu class is a pull down menu component which is displayed on
the menu bar. It inherits the MenuItem class.

Menus are very familiar to programmers in the Windows environment. A


menu has a pull-down list of menu items from which the user can select one at a
time. When many options in multiple categories exist for selection by the user,
menus are the best choice since they take less space on the frame. A click on the
MenuItem generates an ActionEvent and is handled by an ActionListener. A
Menu and a MenuItem are not components since they are not subclasses of the
java.awt.Component class. They are derived from the MenuComponent class.
The following hierarchy illustrates that.

Menu Hierarchy

Menu creation involves many classes, like MenuBar, MenuItem and Menu and
one is added to the other.

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


MenuComponent

A MenuComponent is the highest level class of all menu classes; like a


Component, it is the super most class for all component classes like Button,
Frame etc. A MenuBar is capable of holding the menus and a Menu can hold
menu items. Menus are placed on a menu bar.

Procedure for Creating Menus

The following is the procedure for creating menus:

 Create menu bar


 Add menu bar to the frame
 Create menus
 Add menus to menu bar
 Create menu items
 Add menu items to menus
 Event handling

In the following program, a menu is created and populated with menu items.
User's selected menu item or sub-menu item's

1. import java.awt.*;
2. class AWTMenu extends Frame
3. {
4. MenuBar mbar;
5. Menu menu,submenu;
6. MenuItem m1,m2,m3,m4,m5;
7. public AWTMenu()
8. {
9. // Set frame properties
10. setTitle("AWT Menu"); // Set the title
11. setSize(300,300); // Set size to the frame

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


12. setLayout(new FlowLayout()); // Set the layout
13. setVisible(true); // Make the frame visible
14. setLocationRelativeTo(null); // Center the frame
15. // Create the menu bar
16. mbar=new MenuBar();
17. // Create the menu
18. menu=new Menu("Menu");
19. // Create the submenu
20. submenu=new Menu("Sub Menu");
21. // Create MenuItems
22. m1=new MenuItem("Menu Item 1");
23. m2=new MenuItem("Menu Item 2");
24. m3=new MenuItem("Menu Item 3");
25. m4=new MenuItem("Menu Item 4");
26. m5=new MenuItem("Menu Item 5");
27. // Attach menu items to menu
28. menu.add(m1);
29. menu.add(m2);
30. menu.add(m3);
31. // Attach menu items to submenu
32. submenu.add(m4);
33. submenu.add(m5);
34. // Attach submenu to menu
35. menu.add(submenu);
36. // Attach menu to menu bar
37. mbar.add(menu);
38. // Set menu bar to the frame
39. setMenuBar(mbar);
40. }
41. public static void main(String args[])
42. {
43. new AWTMenu();
44. }
45. }

Sample output of this program:

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Swing

Swing is a part of Java's Java Foundation Classes (JFC) used for building graphical user
interfaces (GUIs). It is built on top of the older Abstract Window Toolkit (AWT) and
provides more powerful and flexible UI components.

Key Features of Swing

Lightweight: Swing components are not dependent on the native OS; instead, they are
rendered by Java itself, making them lightweight.

Platform Independent: Since Swing is part of Java, applications built using Swing can run
on any platform with a compatible JVM.

Rich Set of Components: Swing offers various advanced UI components like tables, trees,
tabbed panes, sliders, etc.

Pluggable Look and Feel (PLAF): Swing allows developers to change the appearance of the
UI without altering the application's functionality.

Event-Driven Programming: Swing follows the event-driven programming model, ensuring


efficient user interaction handling.

MVC Architecture: Swing follows the Model-View-Controller (MVC) design pattern,


separating the data (model) from the UI (view) and the control logic (controller).

Commonly Used Swing Components

Here are some frequently used Swing components:

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Component Description

JFrame Main window of the application

JPanel Container that holds other components

JButton Button for user interaction

JLabel Displays text or images

JTextField Single-line text input field

JTextArea Multi-line text input field

JCheckBox Checkbox for true/false selection

JRadioButton Radio button for selecting one option from a group

JComboBox Drop-down menu

JList List for selecting multiple items

JTable Displays data in table format

JTree Displays hierarchical data

Creating a Simple Swing Application


import javax.swing.*; // Import Swing package

public class SimpleFrame {

public static void main(String[] args) {

// Create a JFrame instance

JFrame frame = new JFrame("My First Swing Frame");

// Set frame size

frame.setSize(400, 300);

// Specify the close operation

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


// Make the frame visible

frame.setVisible(true);

Swing Components

JFrame in Java Swing


JFrame is a key component in Java Swing used to create GUI applications. It represents the
main window of a Swing application where you can add other UI elements like buttons, text
fields, labels, etc.

Key Features of JFrame

Inherits from javax.swing.JFrame.

Acts as a top-level container for other Swing components.

Provides various methods to manage the window’s size, layout, title, visibility, and
closing behavior.

Supports adding menus, buttons, panels, and other elements

Creating a JFrame

A JFrame can be created using two approaches:

1. Using JFrame Constructor

You can create a JFrame object directly and customize it using methods.

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


import javax.swing.*;
public class SimpleFrame {
public static void main(String[] args) {
// Create a JFrame object
JFrame frame = new JFrame("My First JFrame");

// Set size
frame.setSize(400, 300);

// Set default close operation


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Make the frame visible


frame.setVisible(true);
}
}

2. By Extending JFrame Class

Another common approach is to create a class that extends JFrame.t

import javax.swing.*;
public class MyFrame extends JFrame {
public MyFrame() {
// Set title
setTitle("Extended JFrame Example");

// Set size
setSize(400, 300);

// Set default close operation


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Make the frame visible


setVisible(true);

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


}
public static void main(String[] args) {
new MyFrame(); // Create and display the frame
}
}

Key Methods of JFrame

Here are some commonly used JFrame methods for customization:

Method Description

setSize(int width, int height) Sets the width and height of the frame.

setTitle(String title) Sets the title of the window.

setVisible(boolean visible) Controls the visibility of the frame.

setDefaultCloseOperation(int Defines the behavior when closing the frame (e.g.,


operation) EXIT_ON_CLOSE).

setLayout(LayoutManager manager) Specifies the layout for component positioning.

add(Component component) Adds a component (like a button, label, etc.) to the frame.

setLocation(int x, int y) Sets the window's position on the screen.

setResizable(boolean resizable) Controls whether the user can resize the frame.

pack() Automatically sizes the frame based on its content.

JComboBox in Java Swing


JComboBox is a Swing component used to create a drop-down list that allows users to select
one item from a list of options. It is commonly used when there are multiple choices, but only
one option can be selected at a time.

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Key Features of JComboBox

✅ Provides a scrollable drop-down list.


✅ Allows selecting one item at a time.
✅ Can store String, Integer, or custom objects.
✅ Supports adding, removing, and updating items dynamically.
✅ Generates action events when an item is selected.

JComboBox Constructors

The JComboBox class provides several constructors:

Constructor Description
JComboBox() Creates an empty combo box.
JComboBox(Object[] items) Creates a combo box with specified items.
JComboBox(Vector<?> items) Creates a combo box with items stored in a Vector.

Common Methods of JComboBox

Method Description
addItem(Object item) Adds an item to the combo box.
removeItem(Object item) Removes the specified item.
removeAllItems() Removes all items from the combo box.
getSelectedItem() Returns the selected item.
setSelectedItem(Object item) Selects the specified item.
setEditable(boolean flag) Allows the user to type a custom value when set to true.
getItemCount() Returns the total number of items in the combo box.
insertItemAt(Object item, int index) Inserts an item at the specified position.

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Example 1 - Basic JComboBox Example

import javax.swing.*;import java.awt.event.*;


public class ComboBoxExample {
public static void main(String[] args) {
// Create JFrame
JFrame frame = new JFrame("JComboBox Example");

// Create JLabel to display selected item


JLabel label = new JLabel("Selected Item: None");

// Create JComboBox with items


String[] languages = {"Java", "Python", "C++", "JavaScript"};
JComboBox<String> comboBox = new JComboBox<>(languages);

// ActionListener for item selection


comboBox.addActionListener(e -> {
String selected = (String) comboBox.getSelectedItem();
label.setText("Selected Item: " + selected);
});

// Set layout and add components


frame.setLayout(null);
comboBox.setBounds(50, 50, 150, 30);
label.setBounds(50, 100, 200, 30);

frame.add(comboBox);
frame.add(label);

// Frame properties
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


}

ImageIcon in Java Swing


ImageIcon is a class in Java Swing that is used to represent icons and images. It is part of the
javax.swing package and is commonly used with Swing components like JLabel, JButton, or
JFrame to display images.

Key Features of ImageIcon

✅ Supports popular image formats like .jpg, .png, .gif, and .bmp.
✅ Can be resized easily using setIcon() with Image scaling methods.
✅ Efficiently handles image rendering in Swing GUI applications.

ImageIcon Constructor

Constructor Description
ImageIcon(String filename) Loads an image from the specified file path.
ImageIcon(URL url) Loads an image from a specified URL.
ImageIcon(Image image) Creates an ImageIcon from an existing Image object.

Common Methods of ImageIcon

Method Description
getIconWidth() Returns the width of the image.
getIconHeight() Returns the height of the image.
getImage() Returns the Image object stored in the ImageIcon.
setImage(Image image) Sets a new image for the ImageIcon.

Example 1 - Basic ImageIcon Example in JLabel

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


import javax.swing.*;
public class ImageIconExample {
public static void main(String[] args) {
// Create JFrame
JFrame frame = new JFrame("ImageIcon Example");

// Load image using ImageIcon


ImageIcon icon = new ImageIcon("src/images/logo.png");

// Create JLabel and set icon


JLabel label = new JLabel(icon);

// Frame properties
frame.add(label);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Checkbox and Radio Button in Java Swing


Checkboxes and radio buttons are essential UI components used to provide users with options
for selecting one or multiple choices in a graphical user interface (GUI). In Java Swing, these
components are implemented using:

JCheckBox → For multiple selections (checkboxes).

JRadioButton → For single selections within a group (radio buttons).

1. JCheckBox (Checkbox)
The JCheckBox component in Swing allows users to select one or more options from a list.
Each checkbox can be checked (selected) or unchecked (deselected).

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Constructor for JCheckBox
Constructor Description
JCheckBox() Creates an empty checkbox.
JCheckBox(String text) Creates a checkbox with the specified label.
JCheckBox(String text, boolean Creates a checkbox with a label and sets its initial
selected) state.

Common Methods for JCheckBox


Method Description
isSelected() Returns true if the checkbox is selected.
setSelected(boolean b) Sets the checkbox's state (selected/deselected).
getText() Returns the text of the checkbox.

✅ Example: JCheckBox in Swing


import javax.swing.*;import java.awt.*;import java.awt.event.*;
public class CheckBoxExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JCheckBox Example");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

// Creating checkboxes
JCheckBox cb1 = new JCheckBox("Java");
JCheckBox cb2 = new JCheckBox("Python");
JCheckBox cb3 = new JCheckBox("C++");

// Button to display selected options


JButton btn = new JButton("Show Selection");
JLabel resultLabel = new JLabel();

// Button ActionListener

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


btn.addActionListener(e -> {
String selected = "Selected: ";
if (cb1.isSelected()) selected += "Java ";
if (cb2.isSelected()) selected += "Python ";
if (cb3.isSelected()) selected += "C++ ";

resultLabel.setText(selected);
});

// Adding components to frame


frame.add(cb1);
frame.add(cb2);
frame.add(cb3);
frame.add(btn);
frame.add(resultLabel);

frame.setVisible(true);
}
}

2. JRadioButton (Radio Button)


The JRadioButton component is used when only one option should be selected from a group
of options.

Important: To group multiple radio buttons, they must be added to a


ButtonGroup to ensure only one can be selected at a time.

Constructor for JRadioButton


Constructor Description
JRadioButton() Creates an empty radio button.
JRadioButton(String text) Creates a radio button with the specified label.
JRadioButton(String text, boolean Creates a radio button with a label and sets its initial

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Constructor Description
selected) state.

Common Methods for JRadioButton


Method Description
isSelected() Returns true if the radio button is selected.
setSelected(boolean b) Sets the radio button's state (selected/deselected).
getText() Returns the text of the radio button.

✅ Example: JRadioButton in Swing

import javax.swing.*;import java.awt.*;import java.awt.event.*;


public class RadioButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JRadioButton Example");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

// Creating radio buttons


JRadioButton male = new JRadioButton("Male");
JRadioButton female = new JRadioButton("Female");

// Creating ButtonGroup to group radio buttons


ButtonGroup group = new ButtonGroup();
group.add(male);
group.add(female);

// Button to display selected option


JButton btn = new JButton("Show Selection");
JLabel resultLabel = new JLabel();

// Button ActionListener

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


btn.addActionListener(e -> {
if (male.isSelected()) {
resultLabel.setText("Selected: Male");
} else if (female.isSelected()) {
resultLabel.setText("Selected: Female");
} else {
resultLabel.setText("No selection made.");
}
});

// Adding components to frame


frame.add(male);
frame.add(female);
frame.add(btn);
frame.add(resultLabel);

frame.setVisible(true);
}
}

Advanced Swing Components in Java


Java Swing provides several advanced UI components that enhance the graphical user
interface (GUI) experience. Some important advanced Swing components are:

JTabbedPane → For creating tabbed interfaces.

JTree → For displaying hierarchical data.

JTable → For displaying tabular data.

JProgressBar → For visualizing task progress.

1. JTabbedPane (Tabbed Pane)

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


The JTabbedPane component allows switching between multiple panels (tabs) in a single
window.

Constructor for JTabbedPane


Constructor Description
JTabbedPane() Creates an empty tabbed pane.
JTabbedPane(int Specifies tab position (e.g., JTabbedPane.TOP,
tabPlacement) JTabbedPane.LEFT).

Common Methods for JTabbedPane


Method Description
addTab(String title, Component Adds a new tab with the specified title and
comp) component.
setSelectedIndex(int index) Selects the tab at the given index.
getSelectedIndex() Returns the index of the selected tab.

✅ Example: JTabbedPane in Swing


import javax.swing.*;
public class TabbedPaneExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JTabbedPane Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Creating tabbed pane


JTabbedPane tabbedPane = new JTabbedPane();

// Creating panels for tabs


JPanel homePanel = new JPanel();
homePanel.add(new JLabel("Welcome to Home Tab"));

JPanel settingsPanel = new JPanel();


settingsPanel.add(new JLabel("Settings Tab Content"));

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


JPanel aboutPanel = new JPanel();
aboutPanel.add(new JLabel("About Us Content"));

// Adding tabs
tabbedPane.addTab("Home", homePanel);
tabbedPane.addTab("Settings", settingsPanel);
tabbedPane.addTab("About", aboutPanel);

frame.add(tabbedPane);
frame.setVisible(true);
}
}

2. JTree (Tree Structure)


The JTree component is used to represent data in a hierarchical tree-like structure (e.g., folder
directories).

Constructor for JTree


Constructor Description
JTree() Creates an empty tree.
JTree(TreeNode root) Creates a tree with a specified root node.

Common Methods for JTree


Method Description
getSelectionPath() Returns the path of the selected node.
expandRow(int row) Expands the node at the specified row.

✅ Example: JTree in Swing


java
CopyEdit

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


import javax.swing.*;import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JTree Example");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Creating root node


DefaultMutableTreeNode root = new DefaultMutableTreeNode("Files");

// Adding child nodes


DefaultMutableTreeNode documents = new DefaultMutableTreeNode("Documents");
DefaultMutableTreeNode images = new DefaultMutableTreeNode("Images");

documents.add(new DefaultMutableTreeNode("Resume.docx"));
images.add(new DefaultMutableTreeNode("Photo.jpg"));

root.add(documents);
root.add(images);

// Creating tree
JTree tree = new JTree(root);

frame.add(new JScrollPane(tree));
frame.setVisible(true);
}
}

3. JTable (Table Component)


The JTable component is used for displaying data in rows and columns, resembling an Excel
sheet.

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Constructor for JTable
Constructor Description
JTable(Object[][] data, String[] Creates a table with specified data and column
columnNames) names.

Common Methods for JTable


Method Description
getValueAt(int row, int col) Returns the value at the specified cell.
setValueAt(Object value, int row, int col) Updates a cell's value.

✅ Example: JTable in Swing


import javax.swing.*;
public class TableExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JTable Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Data for the table


String[][] data = {
{"1", "Alice", "A"},
{"2", "Bob", "B"},
{"3", "Charlie", "C"}
};

// Column headers
String[] columnNames = {"ID", "Name", "Grade"};

// Creating JTable
JTable table = new JTable(data, columnNames);

// Adding table to a scroll pane


JScrollPane scrollPane = new JScrollPane(table);

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


frame.add(scrollPane);

frame.setVisible(true);
}
}

4. JProgressBar (Progress Bar)


The JProgressBar is used to indicate the progress of a task, such as file downloads, data
processing, etc.

Constructor for JProgressBar


Constructor Description
JProgressBar() Creates a progress bar with default range (0–100).
JProgressBar(int min, int Creates a progress bar with specified minimum and maximum
max) values.

Common Methods for JProgressBar


Method Description
setValue(int value) Sets the progress bar's value.
setStringPainted(boolean b) Displays progress percentage inside the bar.

✅ Example: JProgressBar in Swing


import javax.swing.*;import java.awt.*;import java.awt.event.*;
public class ProgressBarExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JProgressBar Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

// Creating progress bar

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


JProgressBar progressBar = new JProgressBar(0, 100);
progressBar.setStringPainted(true);

// Button to start progress


JButton btn = new JButton("Start Progress");

// Button ActionListener
btn.addActionListener(e -> {
for (int i = 0; i <= 100; i++) {
progressBar.setValue(i);
try {
Thread.sleep(50); // Simulating progress
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
});
// Adding components to frame
frame.add(progressBar);
frame.add(btn);

frame.setVisible(true);
}
}

MVC Architecture in Java (Model-View-Controller)


MVC (Model-View-Controller) is a design pattern widely used in Java for developing
interactive applications with clear separation of concerns. It helps organize code by dividing
an application into three interconnected components — Model, View, and Controller.

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND


Key Components of MVC

Model :

 Represents the data and business logic of the application.


 It directly manages the data, logic, and rules of the application.
 Example: Database connection, data manipulation, etc.

View

 Handles the UI (User Interface).


 Displays data from the Model and sends user interactions to the Controller.
 Example: Swing components like JFrame, JLabel, JTextField, etc.

Controller

 Acts as a bridge between the Model and the View.


 Handles user inputs and updates the Model or View accordingly.
 Example: ActionListeners, Event Handlers, etc.

MVC Flow in Simple Terms

User interacts with the View.

The Controller captures this interaction.

The Controller updates the Model if data changes are required.

The Model notifies the View of data changes.

The View refreshes itself to display updated data

MSBTE NEXT ICON COURSE YOUTUBE CHANNEL – UR ENGINEERING FRIEND

You might also like