Attachment (1)
Attachment (1)
Chapter 4 - K Scheme
Event Handling Using AWT & Swing
Notes
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 करना पडता
है ।
Container in Java :
Types of containers:
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
AWT Controls
Types of Containers
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
public Button();
A few of the methods provided by this class have been listed below:
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.
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();
Below I have listed down the public methods provided by this class:
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.
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
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.
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.*;
{
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");
add(lb1);
add(txt1);
add(lb2);
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) {
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 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
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. };
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.*;
Output
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 {
Output
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
Next card
Last card
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.
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;
Output
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.
Menu Hierarchy
Menu creation involves many classes, like MenuBar, MenuItem and Menu and
one is added to the other.
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
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.
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.
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Swing Components
Provides various methods to manage the window’s size, layout, title, visibility, and
closing behavior.
Creating a JFrame
You can create a JFrame object directly and customize it using methods.
// Set size
frame.setSize(400, 300);
import javax.swing.*;
public class MyFrame extends JFrame {
public MyFrame() {
// Set title
setTitle("Extended JFrame Example");
// Set size
setSize(400, 300);
Method Description
setSize(int width, int height) Sets the width and height of the frame.
add(Component component) Adds a component (like a button, label, etc.) to the frame.
setResizable(boolean resizable) Controls whether the user can resize the frame.
JComboBox 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.
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.
frame.add(comboBox);
frame.add(label);
// Frame properties
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
✅ 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.
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.
// Frame properties
frame.add(label);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
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).
// Creating checkboxes
JCheckBox cb1 = new JCheckBox("Java");
JCheckBox cb2 = new JCheckBox("Python");
JCheckBox cb3 = new JCheckBox("C++");
// Button ActionListener
resultLabel.setText(selected);
});
frame.setVisible(true);
}
}
// Button ActionListener
frame.setVisible(true);
}
}
// Adding tabs
tabbedPane.addTab("Home", homePanel);
tabbedPane.addTab("Settings", settingsPanel);
tabbedPane.addTab("About", aboutPanel);
frame.add(tabbedPane);
frame.setVisible(true);
}
}
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);
}
}
// Column headers
String[] columnNames = {"ID", "Name", "Grade"};
// Creating JTable
JTable table = new JTable(data, columnNames);
frame.setVisible(true);
}
}
// 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);
}
}
Model :
View
Controller