Java 5th Unit Notes
Java 5th Unit Notes
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.
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.
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.
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:
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.
Method Description
public void setSize(int width,int height) Sets the size (width and height) of the component.
public void setLayout(LayoutManager m) Defines the layout manager for the component.
public void setVisible(boolean status) Changes the visibility of the component, by default false.
To create simple AWT example, you need a frame. There are two ways to create a GUI using
Frame in AWT.
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
In this section, we will discuss the MVC Architecture in Java, alongwith its advantages and
disadvantages and examples to understand the implementation of MVC in Java.
The model designs based on the MVC architecture follow MVC design pattern. The application
logic is separated from the user interface while designing the software using model designs.
o Model: It represents the business layer of application. It is an object to carry the data
that can also contain the logic to update controller if data is changed.
o View: It represents the presentation layer of application. It is used to visualize the data
that the model contains.
o Controller: It works on both the model and view. It is used to manage the flow of
application, i.e. data flow in the model object and to update the view whenever data is
changed.
In Java Programming, the Model contains the simple Java classes, the View used to display the
data and the Controller contains the servlets. Due to this separation the user requests are
processed as follows:
1. A client (browser) sends a request to the controller on the server side, for a page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.
o MVC has the feature of scalability that in turn helps the growth of application.
o The components are easy to maintain because there is less dependency.
o A model can be reused by multiple views that provides reusability of code.
o The developers can work with the three layers (Model, View, and Controller)
simultaneously.
o Using MVC, the application becomes more understandable.
o Using MVC, each layer is maintained separately therefore we do not require to deal with
massive code.
o The extending and testing of application is easier.
To implement MVC pattern in Java, we are required to create the following three classes.
The Model in the MVC design pattern acts as a data layer for the application. It represents the
business logic for application and also the state of application. The model object fetch and store
the model state in the database. Using the model layer, rules are applied to the data that
represents the concepts of application.
Let's consider the following code snippet that creates a which is also the first step to implement
MVC pattern.
Employee.java
The above code simply consists of getter and setter methods to the Employee class.
View Layer
As the name depicts, view represents the visualization of data received from the model. The
view layer consists of output of application or user interface. It sends the requested data to the
client, that is fetched from model layer by controller.
Let's take an example where we create a view using the EmployeeView class.
EmployeeView.java
The controller layer gets the user requests from the view layer and processes them, with the
necessary validations. It acts as an interface between Model and View. The requests are then
sent to model for data processing. Once they are processed, the data is sent back to the
controller and then displayed on the view.
Let's consider the following code snippet that creates the controller using the
EmployeeController class.
EmployeeController.java
The following example displays the main file to implement the MVC architecture. Here, we are
using the MVCMain class.
MVCMain.java
1. // main class
2. public class MVCMain {
3. public static void main(String[] args) {
4.
5. // fetching the employee record based on the employee_id from the database
6. Employee model = retriveEmployeeFromDatabase();
7.
8. // creating a view to write Employee details on console
9. EmployeeView view = new EmployeeView();
10.
11. EmployeeController controller = new EmployeeController(model, view);
12.
13. controller.updateView();
14.
15. //updating the model data
16. controller.setEmployeeName("Nirnay");
17. System.out.println("\n Employee Details after updating: ");
18.
19. controller.updateView();
20. }
21.
22. private static Employee retriveEmployeeFromDatabase(){
23. Employee Employee = new Employee();
24. Employee.setName("Anu");
25. Employee.setId("11");
26. Employee.setDepartment("Salesforce");
27. return Employee;
28. }
29. }
The MVCMain class fetches the employee data from the method where we have entered the
values. Then it pushes those values in the model. After that, it initializes the view
(EmployeeView.java). When view is initialized, the Controller (EmployeeController.java) is
invoked and bind it to Employee class and EmployeeView class. At last the updateView()
method (method of controller) update the employee details to be printed to the console.
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 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:
5 public Button();
A few of the methods provided by this class have been listed below:
3
4 //Set the label of this Button instance
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:
1 //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:
1 // Construct a Label with the given text String, of the text alignment
8 public Label();
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.
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.
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI
forms. LayoutManager is an interface that is implemented by all the classes of layout managers.
There are the following classes that represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west,
and center. Each region (area) may contain one component only. It is the default layout of a
frame or window. The BorderLayout provides five constants for each region:
FileName: Border.java
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border
5. {
6. JFrame f;
7. Border()
8. {
9. f = new JFrame();
10.
11. // creating buttons
12. JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
13. JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
14. JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
15. JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
16. JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
17.
18. f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
19. f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
20. f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
21. f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
22. f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
23.
24. f.setSize(300, 300);
25. f.setVisible(true);
26. }
27. public static void main(String[] args) {
28. new Border();
29. }
30. }
Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.
The GridLayout() constructor creates only one row. The following example shows the usage of
the parameterless constructor.
FileName: GridLayoutExample.java
1. // import statements
2. import java.awt.*;
3. import javax.swing.*;
4.
5. public class GridLayoutExample
6. {
7. JFrame frameObj;
8.
9. // constructor
10. GridLayoutExample()
11. {
12. frameObj = new JFrame();
13.
14. // creating 9 buttons
15. JButton btn1 = new JButton("1");
16. JButton btn2 = new JButton("2");
17. JButton btn3 = new JButton("3");
18. JButton btn4 = new JButton("4");
19. JButton btn5 = new JButton("5");
20. JButton btn6 = new JButton("6");
21. JButton btn7 = new JButton("7");
22. JButton btn8 = new JButton("8");
23. JButton btn9 = new JButton("9");
24.
25. // adding buttons to the frame
26. // since, we are using the parameterless constructor, therfore;
27. // the number of columns is equal to the number of buttons we
28. // are adding to the frame. The row count remains one.
29. frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3);
30. frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6);
31. frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9);
32.
33. // setting the grid layout using the parameterless constructor
34. frameObj.setLayout(new GridLayout());
35.
36.
37. frameObj.setSize(300, 300);
38. frameObj.setVisible(true);
39. }
40.
41. // main method
42. public static void main(String argvs[])
43. {
44. new GridLayoutExample();
45. }
46. }
Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one after another (in a
flow). It is the default layout of the applet or panel.
FileName: FlowLayoutExample.java
1. // import statements
2. import java.awt.*;
3. import javax.swing.*;
4.
5. public class FlowLayoutExample
6. {
7.
8. JFrame frameObj;
9.
10. // constructor
11. FlowLayoutExample()
12. {
13. // creating a frame object
14. frameObj = new JFrame();
15.
16. // creating the buttons
17. JButton b1 = new JButton("1");
18. JButton b2 = new JButton("2");
19. JButton b3 = new JButton("3");
20. JButton b4 = new JButton("4");
21. JButton b5 = new JButton("5");
22. JButton b6 = new JButton("6");
23. JButton b7 = new JButton("7");
24. JButton b8 = new JButton("8");
25. JButton b9 = new JButton("9");
26. JButton b10 = new JButton("10");
27.
28.
29. // adding the buttons to frame
30. frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameObj.add(b4);
31. frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frameObj.add(b8);
32. frameObj.add(b9); frameObj.add(b10);
33.
34. // parameter less constructor is used
35. // therefore, alignment is center
36. // horizontal as well as the vertical gap is 5 units.
37. frameObj.setLayout(new FlowLayout());
38.
39. frameObj.setSize(300, 300);
40. frameObj.setVisible(true);
41. }
42.
43. // main method
44. public static void main(String argvs[])
45. {
46. new FlowLayoutExample();
47. }
48. }
Java CardLayout
The Java CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is known as
CardLayout.
The following program uses the next() method to move to the next card of the container.
FileName: CardLayoutExample1.java
1. // import statements
2. import java.awt.*;
3. import javax.swing.*;
4. import java.awt.event.*;
5.
6. public class CardLayoutExample1 extends JFrame implements ActionListener
7. {
8.
9. CardLayout crd;
10.
11. // button variables to hold the references of buttons
12. JButton btn1, btn2, btn3;
13. Container cPane;
14.
15. // constructor of the class
16. CardLayoutExample1()
17. {
18.
19. cPane = getContentPane();
20.
21. //default constructor used
22. // therefore, components will
23. // cover the whole area
24. crd = new CardLayout();
25.
26. cPane.setLayout(crd);
27.
28. // creating the buttons
29. btn1 = new JButton("Apple");
30. btn2 = new JButton("Boy");
31. btn3 = new JButton("Cat");
32.
33. // adding listeners to it
34. btn1.addActionListener(this);
35. btn2.addActionListener(this);
36. btn3.addActionListener(this);
37.
38. cPane.add("a", btn1); // first card is the button btn1
39. cPane.add("b", btn2); // first card is the button btn2
40. cPane.add("c", btn3); // first card is the button btn3
41.
42. }
43. public void actionPerformed(ActionEvent e)
44. {
45. // Upon clicking the button, the next card of the container is shown
46. // after the last card, again, the first card of the container is shown upon clicking
47. crd.next(cPane);
48. }
49.
50. // main method
51. public static void main(String argvs[])
52. {
53. // creating an object of the class CardLayoutExample1
54. CardLayoutExample1 crdl = new CardLayoutExample1();
55.
56. // size is 300 * 300
57. crdl.setSize(300, 300);
58. crdl.setVisible(true);
59. crdl.setDefaultCloseOperation(EXIT_ON_CLOSE);
60. }
61. }
Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along
their baseline.
The components may not be of the same size. Each GridBagLayout object maintains a dynamic,
rectangular grid of cells. Each component occupies one or more cells known as its display area.
Each component associates an instance of GridBagConstraints. With the help of the constraints
object, we arrange the component's display area on the grid. The GridBagLayout manages each
component's minimum and preferred sizes in order to determine the component's size.
GridBagLayout components are also arranged in the rectangular grid but can have many
different sizes and can occupy multiple rows or columns.
Constructor
GridBagLayout(): The parameterless constructor is used to create a grid bag layout manager.
GridBagLayout Fields
GridBagLayout Methods
protected getLayoutInfo(Container parent, int sizeflag) This method is obsolete and supplied
GridBagLayoutInfo for backwards compatibility.
Example 1
FileName: GridBagLayoutExample.java
1. import java.awt.Button;
2. import java.awt.GridBagConstraints;
3. import java.awt.GridBagLayout;
4.
5. import javax.swing.*;
6. public class GridBagLayoutExample extends JFrame{
7. public static void main(String[] args) {
8. GridBagLayoutExample a = new GridBagLayoutExample();
9. }
10. public GridBagLayoutExample() {
11. GridBagLayoutgrid = new GridBagLayout();
12. GridBagConstraints gbc = new GridBagConstraints();
13. setLayout(grid);
14. setTitle("GridBag Layout Example");
15. GridBagLayout layout = new GridBagLayout();
16. this.setLayout(layout);
17. gbc.fill = GridBagConstraints.HORIZONTAL;
18. gbc.gridx = 0;
19. gbc.gridy = 0;
20. this.add(new Button("Button One"), gbc);
21. gbc.gridx = 1;
22. gbc.gridy = 0;
23. this.add(new Button("Button two"), gbc);
24. gbc.fill = GridBagConstraints.HORIZONTAL;
25. gbc.ipady = 20;
26. gbc.gridx = 0;
27. gbc.gridy = 1;
28. this.add(new Button("Button Three"), gbc);
29. gbc.gridx = 1;
30. gbc.gridy = 1;
31. this.add(new Button("Button Four"), gbc);
32. gbc.gridx = 0;
33. gbc.gridy = 2;
34. gbc.fill = GridBagConstraints.HORIZONTAL;
35. gbc.gridwidth = 2;
36. this.add(new Button("Button Five"), gbc);
37. setSize(300, 300);
38. setPreferredSize(getSize());
39. setVisible(true);
40. setDefaultCloseOperation(EXIT_ON_CLOSE);
41.
42. }
43.
44. }
A user interacts with the application by pressing either keys on the keyboard or by using
mouse. A programmer should know which key the user has pressed on the keyboard or
whether the mouse is moved, pressed, or released. These are also called ‘events’. Knowing
these events will enable the programmer to write his code according to the key pressed or
mouse event.
1. Public void keyPressed(KeyEvent ke): This method is called when a key is pressed
on the keyboard. This include any key on the keyboard along with special keys like
function keys, shift, alter, caps lock, home, end etc.
2. Public void keyTyped(keyEvent ke) : This method is called when a key is typed on
the keyboard. This is same as keyPressed() method but this method is called when
general keys like A to Z or 1 to 9 etc are typed. It cannot work with special keys.
3. Public void keyReleased(KeyEvent ke): this method is called when a key is release.
KeyEvent class has the following methods to know which key is typed by the user.
1. Char getKeyChar(): this method returns the key name (or character) related to the key
pressed or released.
2. Int getKeyCode(): this method returns an integer number which is the value of the
key presed by the user.
The follwing are the key codes for the keys on the keyboard. They are defined as
constants in KeyEvent class. Remember VK represents Virtual Key.
package com.myPack;
{
private static final Font Font = null;Container c;
JTextArea a;
c.add(a);
a.addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{
int keycode = ke.getKeyCode();
if(keycode == KeyEvent.VK_F1) str += "F1 Key"; if(keycode ==
KeyEvent.VK_F2) str += "F2 Key"; if(keycode == KeyEvent.VK_F3) str
+= "F3 Key"; if(keycode == KeyEvent.VK_PAGE_UP) str += "Page UP";
if(keycode == KeyEvent.VK_PAGE_DOWN) str += "Page Down";
a.setText(str);
str =" " ;
}
public void keyRelease(KeyEvent ke)
{
}
public void keyTyped(KeyEvent ke)
{
}
public static void main(String args[])
{
KeyBoardEvents kbe = new KeyBoardEvents();
kbe.setSize(400,400); kbe.setVisible(true);
kbe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void keyReleased(KeyEvent arg0) {
Output:
The user may click, release, drag, or move a mouse while interacting with athe
application. If the programmer knows what the user has done, he can write the code
according to the mouse events. To trap the mouse events, MouseListener and
MouseMotionListener interfaces of java.awt.event package are use.
1. int getButton(): this method returns a value representing a mouse button, when it
is clicked it retursn 1 if left button is clicked, 2 if middle button, and 3 if right
button is clicked.
2. int getX(); this method returns the horizontal x position of the event relative to the
source component.
3. int getY(); this method returns the vertical y postion of the event relative to the
source component.
Program to create a text area and display the mouse event when the button on the
mouse is clicke, when mouse is moved, etc. is done by user.
package com.myPack;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
{
String str =" ";
JTextArea ta;
Container c;
int x, y;
MouseEvents()
{
c=getContentPane();
c.setLayout(new FlowLayout());
{
int i = me.getButton();
if(i==1)
}
public void mouseEntered(MouseEvent me)
{
str += "Mouse Entered";
this.display();
}
public void mouseExited(MouseEvent me)
{
str += "Mouse Exited";
this.display();
}
public void mousePressed(MouseEvent me)
{
x = me.getX();
y= me.getY();
str += "Mouse Pressed at :" +x + "\t" + y;
this.display();
}
public void mouseReleased(MouseEvent me)
{
x = me.getX();
y= me.getY();
str += "Mouse Released at :" +x + "\t" + y;
this.display();
}
public void mouseDragged(MouseEvent me)
{
x = me.getX();
y= me.getY();
str += "Mouse Dragged at :" +x + "\t" + y;
this.display();
}
public void mouseMoved(MouseEvent me)
{
x = me.getX();
y= me.getY();
str += "Mouse Moved at :" +x + "\t" + y;
this.display();
{
ta.setText(str);
str=" ";
}
{
MouseEvents mes = new MouseEvents();
mes.setSize(400,400);
mes.setVisible(true);
mes.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output:
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
• Applets are designed just for handling the client site problems.
while the javaapplications are designed to work with the client as
well as server.
• Applications are not too small to embed into a html page so that
the user can view theapplication in your browser. On the other
hand applet have the accessibility criteria ofthe resources
Painting in Applet
1. import java.awt.*;
2. import java.awt.event.*;
3. import java.applet.*;
4. public class MouseDrag extends Applet implements MouseMotionListener{
5.
6. public void init(){
7. addMouseMotionListener(this);
8. setBackground(Color.red);
9. }
10.
11. public void mouseDragged(MouseEvent me){
12. Graphics g=getGraphics();
13. g.setColor(Color.white);
14. g.fillOval(me.getX(),me.getY(),5,5);
15. }
16. public void mouseMoved(MouseEvent me){}
17.
18. }
In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis and y-axis. The
getGraphics() method of Component class returns the object of Graphics.
myapplet.html
1. <html>
2. <body>
3. <applet code="MouseDrag.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
In Java, an applet is a special type of program embedded in the web page to generate dynamic
content. Applet is a class in Java.
The applet life cycle can be defined as the process of how the object is created, started, stopped,
and destroyed during the entire execution of its application. It basically has five core methods
namely init(), start(), stop(), paint() and destroy().These methods are invoked by the browser to
execute.
Along with the browser, the applet also works on the client side, thus having less processing
time.
There are five methods of an applet life cycle, and they are:
o init(): The init() method is the first method to run that initializes the applet. It can be
invoked only once at the time of initialization. The web browser creates the initialized
objects, i.e., the web browser (after checking the security settings) runs the init() method
within the applet.
o start(): The start() method contains the actual code of the applet and starts the applet. It
is invoked immediately after the init() method is invoked. Every time the browser is
loaded or refreshed, the start() method is invoked. It is also invoked whenever the applet
is maximized, restored, or moving from one tab to another in the browser. It is in an
inactive state until the init() method is invoked.
o stop(): The stop() method stops the execution of the applet. The stop () method is
invoked whenever the applet is stopped, minimized, or moving from one tab to another in
the browser, the stop() method is invoked. When we go back to that page, the start()
method is invoked again.
o destroy(): The destroy() method destroys the applet after its work is done. It is invoked
when the applet window is closed or when the tab containing the webpage is closed. It
removes the applet object from memory and is executed only once. We cannot start the
applet once it is destroyed.
o paint(): The paint() method belongs to the Graphics class in Java. It is used to draw
shapes like circle, square, trapezium, etc., in the applet. It is executed after the start()
method and when the browser or applet windows are resized.
1. init()
2. start()
3. paint()
1. stop()
2. destroy()
These methods are invoked by the browser automatically. There is no need to call them
explicitly.
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and fee
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane etc
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
The methods of Component class are widely used in java swing that are given below.
Method Description
public void setVisible(boolean b) sets the visibility of the component. It is by default false.
We can write the code of swing inside the main(), constructor or any other method.
Let's see a simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.
File: FirstSwingExample.java
1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
8.
9. f.add(b);//adding button in JFrame
10.
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers
13. f.setVisible(true);//making the frame visible
14. }
15. }
Swing components
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent class.
Constructor Description
JLabel() Creates a JLabel instance with no image and with an empty string
for the title.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and
horizontalAlignment) horizontal alignment.
Commonly used Methods:
Methods Description
void setText(String text) It defines the single line of text this component will display.
void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents along the X axis.
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the X axis.
Java JTextField
The object of a JTextField class is a text component that allows the editing of a single line text. It
inherits JTextComponent class.
Constructor Description
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int columns) Creates a new TextField initialized with the specified text and columns.
JTextField(int columns) Creates a new empty TextField with the specified number of columns.
Methods Description
void addActionListener(ActionListener l) It is used to add the specified action listener to receive action even
from this textfield.
Action getAction() It returns the currently set Action for this ActionEvent source, or
null if no Action is set.
Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
Constructor Description
Methods Description
Output:
Java JToggleButton
Nested Classes
Constructors
Constructor Description
JToggleButton() It creates an initially unselected toggle button without setting the
text or image.
JToggleButton(Action a) It creates a toggle button where properties are taken from the
Action supplied.
JToggleButton(Icon icon) It creates an initially unselected toggle button with the specified
image but no text.
JToggleButton(Icon icon, boolean selected) It creates a toggle button with the specified image and selection
state, but no text.
JToggleButton(String text) It creates an unselected toggle button with the specified text.
JToggleButton(String text, boolean It creates a toggle button with the specified text and selection
selected) state.
JToggleButton(String text, Icon icon) It creates a toggle button that has the specified text and image,
and that is initially unselected.
JToggleButton(String text, Icon icon, It creates a toggle button with the specified text, image, and
boolean selected) selection state.
Methods
Void updateUI() It resets the UI property to a value from the current look and
feel.
JToggleButton Example
1. import java.awt.FlowLayout;
2. import java.awt.event.ItemEvent;
3. import java.awt.event.ItemListener;
4. import javax.swing.JFrame;
5. import javax.swing.JToggleButton;
6.
7. public class JToggleButtonExample extends JFrame implements ItemListener {
8. public static void main(String[] args) {
9. new JToggleButtonExample();
10. }
11. private JToggleButton button;
12. JToggleButtonExample() {
13. setTitle("JToggleButton with ItemListener Example");
14. setLayout(new FlowLayout());
15. setJToggleButton();
16. setAction();
17. setSize(200, 200);
18. setVisible(true);
19. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. }
21. private void setJToggleButton() {
22. button = new JToggleButton("ON");
23. add(button);
24. }
25. private void setAction() {
26. button.addItemListener(this);
27. }
28. public void itemStateChanged(ItemEvent eve) {
29. if (button.isSelected())
30. button.setText("OFF");
31. else
32. button.setText("ON");
33. }
34. }
Output
Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.
JCheckBox class declaration
Constructor Description
JJCheckBox() Creates an initially unselected check box button with no text, no icon.
JCheckBox(String text, boolean Creates a check box with text and specifies whether or not it is initially
selected) selected.
JCheckBox(Action a) Creates a check box where properties are taken from the Action
supplied.
Output:
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.
Constructor Description
JRadioButton(String s, boolean selected) Creates a radio button with the specified text and selected status.
Methods Description
Java JTabbedPane
The JTabbedPane class is used to switch between a group of components by clicking on a tab
with a given title or icon. It inherits JComponent class.
Constructor Description
JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab placement and
tabLayoutPolicy) tab layout policy.
Java JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is limited, we
use a scroll pane to display a large component or a component whose size can change
dynamically.
Constructors
Constructor Purpose
JScrollPane() It creates a scroll pane. The Component parameter, when present, sets the scroll
pane's client. The two int parameters, when present, set the vertical and horizonta
JScrollPane(Component) scroll bar policies (respectively).
JScrollPane(int, int)
JScrollPane(Component,
int, int)
Useful Methods
void setColumnHeaderView(Component) It sets the column header for the scroll pane.
void setRowHeaderView(Component) It sets the row header for the scroll pane.
void setCorner(String, Component) It sets or gets the specified corner. The int parameter
specifies which corner and must be one of the following
Component getCorner(String) constants defined in ScrollPaneConstants:
UPPER_LEFT_CORNER, UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER, LOWER_RIGHT_CORNER
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.
JScrollPane Example
1. import java.awt.FlowLayout;
2. import javax.swing.JFrame;
3. import javax.swing.JScrollPane;
4. import javax.swing.JtextArea;
5.
6. public class JScrollPaneExample {
7. private static final long serialVersionUID = 1L;
8.
9. private static void createAndShowGUI() {
10.
11. // Create and set up the window.
12. final JFrame frame = new JFrame("Scroll Pane Example");
13.
14. // Display the window.
15. frame.setSize(500, 500);
16. frame.setVisible(true);
17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18.
19. // set flow layout for the frame
20. frame.getContentPane().setLayout(new FlowLayout());
21.
22. JTextArea textArea = new JTextArea(20, 20);
23. JScrollPane scrollableTextArea = new JScrollPane(textArea);
24.
25. scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_
ALWAYS);
26. scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWA
YS);
27.
28. frame.getContentPane().add(scrollableTextArea);
29. }
30. public static void main(String[] args) {
31.
32.
33. javax.swing.SwingUtilities.invokeLater(new Runnable() {
34.
35. public void run() {
36. createAndShowGUI();
37. }
38. });
39. }
40. }
Output:
Java JList
The object of JList class represents a list of text items. The list of text items can be set up so that
the user can choose either one item or multiple items. It inherits JComponent class.
Constructor Description
JList(ary[] listData) Creates a JList that displays the elements in the specified array.
JList(ListModel<ary> dataModel) Creates a JList that displays elements from the specified, non-null, model.
Commonly used Methods:
Methods Description
ListModel getModel() It is used to return the data model that holds a list of
items displayed by the JList component.
Output:
Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.
Constructor Description
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified array.
JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in the specified Vector.
Methods Description
void removeAllItems() It is used to remove all the items from the list.
void setEditable(boolean b) It is used to determine whether the JComboBox is editable.
Output:
Java JComboBox Example with ActionListener
1. import javax.swing.*;
2. import java.awt.event.*;
3. public class ComboBoxExample {
4. JFrame f;
5. ComboBoxExample(){
6. f=new JFrame("ComboBox Example");
7. final JLabel label = new JLabel();
8. label.setHorizontalAlignment(JLabel.CENTER);
9. label.setSize(400,100);
10. JButton b=new JButton("Show");
11. b.setBounds(200,100,75,20);
12. String languages[]={"C","C++","C#","Java","PHP"};
13. final JComboBox cb=new JComboBox(languages);
14. cb.setBounds(50, 100,90,20);
15. f.add(cb); f.add(label); f.add(b);
16. f.setLayout(null);
17. f.setSize(350,350);
18. f.setVisible(true);
19. b.addActionListener(new ActionListener() {
20. public void actionPerformed(ActionEvent e) {
21. String data = "Programming language Selected: "
22. + cb.getItemAt(cb.getSelectedIndex());
23. label.setText(data);
24. }
25. });
26. }
27. public static void main(String[] args) {
28. new ComboBoxExample();
29. }
30. }
Output: