0% found this document useful (0 votes)
1 views74 pages

Java 5th Unit Notes

Java AWT (Abstract Window Toolkit) is an API for developing GUI applications in Java, featuring platform-dependent components that utilize the underlying OS resources. It includes various classes for components like buttons and text fields, and supports a robust event-handling model along with layout managers. The document also discusses the MVC architecture in Java, explaining its components (Model, View, Controller) and providing examples of implementation.
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)
1 views74 pages

Java 5th Unit Notes

Java AWT (Abstract Window Toolkit) is an API for developing GUI applications in Java, featuring platform-dependent components that utilize the underlying OS resources. It includes various classes for components like buttons and text fields, and supports a robust event-handling model along with layout managers. The document also discusses the MVC architecture in Java, explaining its components (Model, View, Controller) and providing examples of implementation.
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/ 74

Java AWT

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.

Why AWT is platform independent?

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

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

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

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.
Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.

Components

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

Container

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

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

Types of containers:

There are four types of containers in Java AWT:

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

Window

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

Panel

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

Frame

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

Useful Methods of Component Class

Method Description

public void add(Component c) Inserts a component on this component.

public void setSize(int 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.

Java AWT Example

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

1. By extending Frame class (inheritance)


2. By creating the object of Frame class (association)

AWT Example by Inheritance

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

AWTExample1.java

1. // importing Java AWT class


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

MVC Architecture in Java

The Model-View-Controller (MVC) is a well-known design pattern in the web development


field. It is way to organize our code. It specifies that a program or application shall consist of
data model, presentation information and control information. The MVC pattern needs all these
components to be separated as different objects.

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.

What is MVC architecture 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.

The MVC pattern architecture consists of three layers:

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.

Advantages of MVC Architecture

The advantages of MVC architecture are as follows:

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.

Implementation of MVC using Java

To implement MVC pattern in Java, we are required to create the following three classes.

o Employee Class, will act as model layer


o EmployeeView Class, will act as a view layer
o EmployeeContoller Class, will act a controller layer

MVC Architecture Layers


Model Layer

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

1. // class that represents model


2. public class Employee {
3.
4. // declaring the variables
5. private String EmployeeName;
6. private String EmployeeId;
7. private String EmployeeDepartment;
8.
9. // defining getter and setter methods
10. public String getId() {
11. return EmployeeId;
12. }
13.
14. public void setId(String id) {
15. this.EmployeeId = id;
16. }
17.
18. public String getName() {
19. return EmployeeName;
20. }
21.
22. public void setName(String name) {
23. this.EmployeeName = name;
24. }
25.
26. public String getDepartment() {
27. return EmployeeDepartment;
28. }
29.
30. public void setDepartment(String Department) {
31. this.EmployeeDepartment = Department;
32. }
33.
34. }

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

1. // class which represents the view


2. public class EmployeeView {
3.
4. // method to display the Employee details
5. public void printEmployeeDetails (String EmployeeName, String EmployeeId, String Employe
eDepartment){
6. System.out.println("Employee Details: ");
7. System.out.println("Name: " + EmployeeName);
8. System.out.println("Employee ID: " + EmployeeId);
9. System.out.println("Employee Department: " + EmployeeDepartment);
10. }
11. }
Controller Layer

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

1. // class which represent the controller


2. public class EmployeeController {
3.
4. // declaring the variables model and view
5. private Employee model;
6. private EmployeeView view;
7.
8. // constructor to initialize
9. public EmployeeController(Employee model, EmployeeView view) {
10. this.model = model;
11. this.view = view;
12. }
13.
14. // getter and setter methods
15. public void setEmployeeName(String name){
16. model.setName(name);
17. }
18.
19. public String getEmployeeName(){
20. return model.getName();
21. }
22.
23. public void setEmployeeId(String id){
24. model.setId(id);
25. }
26.
27. public String getEmployeeId(){
28. return model.getId();
29. }
30.
31. public void setEmployeeDepartment(String Department){
32. model.setDepartment(Department);
33. }
34.
35. public String getEmployeeDepartment(){
36. return model.getDepartment();
37. }
38.
39. // method to update view
40. public void updateView() {
41. view.printEmployeeDetails(model.getName(), model.getId(), model.getDepartment());
42. }
43. }
Main Class Java file

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:

1 //Construct a Button with the given label

2 public Button(String btnLabel);

4 //Construct a Button with empty label

5 public Button();

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

1 //Get the label of this Button instance

2 public String getLabel();

3
4 //Set the label of this Button instance

5 public void setLabel(String btnLabel);

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

8 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:

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

2 public TextField(String initialText, int columns);

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

5 public TextField(String initialText);

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

8 public TextField(int columns);

A few of the methods provided by TextField class are:

1 // Get the current text on this TextField instance

2 public String getText();

4 // Set the display text on this TextField instance

5 public void setText(String strText);

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

7 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:
1 // Construct a Label with the given text String, of the text alignment

2 public Label(String strLabel, int alignment);

4 //Construct a Label with the given text String

5 public Label(String strLabel);

7 //Construct an initially empty Label

8 public Label();

This class also provides 3 constants which are:

1 public static final LEFT; // Label.LEFT

3 public static final RIGHT; // Label.RIGHT

5 public static final CENTER; // Label.CENTER

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:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:


o BorderLayout(): creates a border layout but with no gaps between the components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal
and vertical gaps between the components.
Example of BorderLayout class: Using BorderLayout() constructor

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.

Constructors of GridLayout class


1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns along with given horizontal and vertical gaps.

Example of GridLayout class: Using GridLayout() Constructor

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.

Fields of FlowLayout class


1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Constructors of FlowLayout class
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5
unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.

Example of FlowLayout class: Using FlowLayout() constructor

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.

Constructors of CardLayout Class


1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.

Commonly Used Methods of CardLayout Class


o public void next(Container parent): is used to flip to the next card of the given
container.
o public void previous(Container parent): is used to flip to the previous card of the
given container.
o public void first(Container parent): is used to flip to the first card of the given
container.
o public void last(Container parent): is used to flip to the last card of the given
container.
o public void show(Container parent, String name): is used to flip to the specified card
with the given name.

Example of CardLayout Class: Using Default Constructor

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

Modifier and Type Field Description

double[] columnWeights It is used to hold the overrides to the


column weights.

int[] columnWidths It is used to hold the overrides to the


column minimum width.

protected comptable It is used to maintains the associatio


Hashtable<Component,GridBagConstraints> between a component and its gridba
constraints.

protected GridBagConstraints defaultConstraints It is used to hold a gridbag constrain


instance containing the default value
protected GridBagLayoutInfo layoutInfo It is used to hold the layout informa
for the gridbag.

protected static int MAXGRIDSIZE No longer in use just for backward


compatibility

protected static int MINSIZE It is smallest grid that can be laid ou


by the grid bag layout.

protected static int PREFERREDSIZE It is preferred grid size that can be la


out by the grid bag layout.

int[] rowHeights It is used to hold the overrides to the


row minimum heights.

double[] rowWeights It is used to hold the overrides to the


row weights.

GridBagLayout Methods

Modifier and Type Method Description

Void addLayoutComponent(Component comp, It adds specified component to the


Object constraints) layout, using the specified constrain
object.

Void addLayoutComponent(String name, It has no effect, since this layout


Component comp) manager does not use a per-compon
string.

protected void adjustForGravity(GridBagConstraints It adjusts the x, y, width, and height


constraints, Rectangle r) fields to the correct values dependin
on the constraint geometry and pads

protected void AdjustForGravity(GridBagConstraints This method is for backwards


constraints, Rectangle r) compatibility only
protected void arrangeGrid(Container parent) Lays out the grid.

protected void ArrangeGrid(Container parent) This method is obsolete and supplied


for backwards compatibility

GridBagConstraints getConstraints(Component comp) It is for getting the constraints for th


specified component.

Float getLayoutAlignmentX(Container parent) It returns the alignment along the x


axis.

Float getLayoutAlignmentY(Container parent) It returns the alignment along the y


axis.

int[][] getLayoutDimensions() It determines column widths and row


heights for the layout grid.

protected getLayoutInfo(Container parent, int sizeflag) This method is obsolete and supplied
GridBagLayoutInfo for backwards compatibility.

protected GetLayoutInfo(Container parent, int This method is obsolete and supplied


GridBagLayoutInfo sizeflag) for backwards compatibility.

Point getLayoutOrigin() It determines the origin of the layout


area, in the graphics coordinate spac
the target container.

double[][] getLayoutWeights() It determines the weights of the layo


grid's columns and rows.

protected Dimension getMinSize(Container parent, It figures out the minimum size of th


GridBagLayoutInfo info) master based on the information from
getLayoutInfo.
protected Dimension GetMinSize(Container parent, This method is obsolete and supplied
GridBagLayoutInfo info) for backwards compatibility only

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. }

Handling Keyboard Events

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.

KeyListener interface of java.awt.event package helps to know which key is pressed or


released by the user. It has 3 methods

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.

• To represent keys from a to z : VK_A to VK_Z.


• To represent keys from 1 to 9: VK_0 to VK_9.
• To represent keys from F1 to F12: VK_F1 to VK_F12.
• To represent home, end : VK_HOME, VK_END.
• To represent PageUp, PageDown: VK_PAGE_UP, VK_PAGE_DOWN
• To represent Insert, Delete: VK_INSERT, VK_DELETE
• To represent caps lock: VK_CAPS_LOCK
• To represent alter key: VK_ALT
• To represent Control Key: VK_CONTROL
• To represent shift: VK_SHIFT
• To represent tab key: VK_TAB
• To represent arrow keys: VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN
• To represent Escape key: VK_ESCAPE
• Static String getKeyText(int keyCode); this method returns a string describing the
keyCode such as HOME, F1 or A.
Program: to trap a key which is pressed on the keyboard and display its name in the
text area.

package com.myPack;

import java.awt.*; import


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

class KeyBoardEvents extends JFrame implements KeyListener

{
private static final Font Font = null;Container c;

JTextArea a;

String str = " ";


KeyBoardEvents()
{
c=getContentPane();
a = new JTextArea("Press a Key");

a.setFont(new Font ("Times New Roman", Font.BOLD,30));

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) {

// TODO Auto-generated method stub

Output:

Handling Mouse Events

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.

MouseListener interface has the following methods.

1. void mouseClicked(MouseEvent e); void MouseClicked this method is invoked


when the mouse button has been clicked(pressed and released) on a component.
2. void mouseEntered(MouseEvent e): this method is invoked when the mouse enters
a component.
3. void mouseExited(MouseEvent e): this method is invoked when the mouse exits a
component
4. void mousePressed(MouseEvent e): this method is invoked when a mouse button
has been pressed on a component.
5. void mouseRelease(MouseEvent e): this method is invoked when a mouse button
has been released ona component.

MouseMotionListener interface has the following methods.

1. void mouseDragged(MouseEvent e): this method is invoked when a mouse button is


pressed on a component and then dragged.
2. void mouseMoved(MouseEvent e): this method is invoked when a mouse cursor has
been moved onto a component and then dragged.
The MouseEVent class has the following methods

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.*;

class MouseEvents extends JFrame implements MouseListener, MouseMotionListener

{
String str =" ";
JTextArea ta;
Container c;
int x, y;

MouseEvents()
{
c=getContentPane();
c.setLayout(new FlowLayout());

ta = new JTextArea("Click the mouse or move it", 5, 20);


ta.setFont(new Font("Arial", Font.BOLD, 30));
c.add(ta);
ta.addMouseListener(this);
ta.addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent me)

{
int i = me.getButton();
if(i==1)

str+= "Clicked Button : Left";


else if(i==2)

str+= "Clicked Button : Middle";


else if(i==3)

str+= "Clicked Button : Right";


this.display();

}
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();

public void display()

{
ta.setText(str);
str=" ";
}

public static void main(String args[])

{
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

There are many advantages of applet. They are as follows:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.
There are two kinds of Java programs, applications (also called stand-
alone programs) and Applets. An Applet is a small Internet-based
program that has the Graphical User Interface(GUI), written in the Java
programming language.
Applets are designed to run inside a web browser or in applet
viewer to facilitate the user to animate the graphics, play sound, and
design the GUI components such as text box, button, and radio button.
When applet arrives on the client, it has limited access to resources, so
that it can produce arbitary multimedia user interface and run complex
computation without introducing the risk of viruses or breaching data
integrity.
To create an applet, we extend the ―java.applet.Applet‖
class And by overridingthe methods of java.awt.Applet, new
functionality can be placed into web pages.
Applet vs Application

• Applets as previously described, are the small programs while


applications arelarger programs

• Applets don't have the main method while in an application


execution starts withthe main method

• 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 designed to exists in a secure area. while the


applets are typically used

• 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

We can perform painting operation in applet by the mouseDragged() method of MouseMotionListener.

Example of 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>

Applet Life Cycle in Java

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.

Methods of Applet Life Cycle

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.

Sequence of method execution when an applet is executed:

1. init()
2. start()
3. paint()

Sequence of method execution when an applet is executed:

1. stop()
2. destroy()

Applet Life Cycle Working


o The Java plug-in software is responsible for managing the life cycle of an applet.
o An applet is a Java application executed in any web browser and works on the client-side.
It doesn't have the main() method because it runs in the browser. It is thus created to be
placed on an HTML page.
o The init(), start(), stop() and destroy() methods belongs to the applet.Applet class.
o The paint() method belongs to the awt.Component class.
o In Java, if we want to make a class an Applet class, we need to extend the Applet
o Whenever we create an applet, we are creating the instance of the existing Applet class.
And thus, we can use all the methods of that class.

Flow of Applet Life Cycle:

These methods are invoked by the browser automatically. There is no need to call them
explicitly.

Syntax of entire Applet Life Cycle in Java


1. class TestAppletLifeCycle extends Applet {
2. public void init() {
3. // initialized objects
4. }
5. public void start() {
6. // code to start the applet
7. }
8. public void paint(Graphics graphics) {
9. // draw the shapes
10. }
11. public void stop() {
12. // code to stop the applet
13. }
14. public void destroy() {
15. // code to destroy the applet
16. }
17. }

Java Swing Tutorial

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.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing

No. Java AWT Java Swing


1) AWT components are platform-dependent. Java swing components are platform-
independent.

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

3) AWT doesn't support pluggable look and 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

5) AWT doesn't follows MVC(Model View Controller) Swing follows MVC.


where model represents data, view represents presentation
and controller acts as an interface between model and view.

What is JFC

The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.

Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.


Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int height) sets size of the component.


public void setLayout(LayoutManager m) sets the layout manager for the component.

public void setVisible(boolean b) sets the visibility of the component. It is by default false.

Java Swing Examples

There are two ways to create a frame:

o By creating the object of Frame class (association)


o By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example

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.

JLabel class declaration

Let's see the declaration for javax.swing.JLabel class.

1. public class JLabel extends JComponent implements SwingConstants, Accessible


Commonly used Constructors:

Constructor Description

JLabel() Creates a JLabel instance with no image and with an empty string
for the title.

JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and
horizontalAlignment) horizontal alignment.
Commonly used Methods:

Methods Description

String getText() t returns the text string that a label displays.

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 JLabel Example


1. import javax.swing.*;
2. class LabelExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("Label Example");
7. JLabel l1,l2;
8. l1=new JLabel("First Label.");
9. l1.setBounds(50,50, 100,30);
10. l2=new JLabel("Second Label.");
11. l2.setBounds(50,100, 100,30);
12. f.add(l1); f.add(l2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }
Java JLabel Example with ActionListener
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class LabelExample extends Frame implements ActionListener{
5. JTextField tf; JLabel l; JButton b;
6. LabelExample(){
7. tf=new JTextField();
8. tf.setBounds(50,50, 150,20);
9. l=new JLabel();
10. l.setBounds(50,100, 250,20);
11. b=new JButton("Find IP");
12. b.setBounds(50,150,95,30);
13. b.addActionListener(this);
14. add(b);add(tf);add(l);
15. setSize(400,400);
16. setLayout(null);
17. setVisible(true);
18. }
19. public void actionPerformed(ActionEvent e) {
20. try{
21. String host=tf.getText();
22. String ip=java.net.InetAddress.getByName(host).getHostAddress();
23. l.setText("IP of "+host+" is: "+ip);
24. }catch(Exception ex){System.out.println(ex);}
25. }
26. public static void main(String[] args) {
27. new LabelExample();
28. } }

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.

JTextField class declaration

Let's see the declaration for javax.swing.JTextField class.

1. public class JTextField extends JTextComponent implements SwingConstants


Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

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.

Commonly used Methods:

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.

void setFont(Font f) It is used to set the current font.


void It is used to remove the specified action listener so that it no longe
removeActionListener(ActionListener l) receives action events from this textfield.

Java JTextField Example


1. import javax.swing.*;
2. class TextFieldExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("TextField Example");
7. JTextField t1,t2;
8. t1=new JTextField("Welcome to Javatpoint.");
9. t1.setBounds(50,100, 200,30);
10. t2=new JTextField("AWT Tutorial");
11. t2.setBounds(50,150, 200,30);
12. f.add(t1); f.add(t2);
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }

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.

JButton class declaration

Let's see the declaration for javax.swing.JButton class.

1. public class JButton extends AbstractButton implements Accessible


Commonly used Constructors:

Constructor Description

JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.

Commonly used Methods of AbstractButton class:

Methods Description

void setText(String s) It is used to set specified text on button

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

Java JButton Example


1. import javax.swing.*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame("Button Example");
5. JButton b=new JButton("Click Here");
6. b.setBounds(50,100,95,30);
7. f.add(b);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. }

Output:

Java JButton Example with ActionListener


1. import java.awt.event.*;
2. import javax.swing.*;
3. public class ButtonExample {
4. public static void main(String[] args) {
5. JFrame f=new JFrame("Button Example");
6. final JTextField tf=new JTextField();
7. tf.setBounds(50,50, 150,20);
8. JButton b=new JButton("Click Here");
9. b.setBounds(50,100,95,30);
10. b.addActionListener(new ActionListener(){
11. public void actionPerformed(ActionEvent e){
12. tf.setText("Welcome to Javatpoint.");
13. }
14. });
15. f.add(b);f.add(tf);
16. f.setSize(400,400);
17. f.setLayout(null);
18. f.setVisible(true);
19. }
20. }

Java JToggleButton

JToggleButton is used to create toggle button, it is two-states button to switch on or off.

Nested Classes

Modifier and Class Description


Type

protected class JToggleButton.AccessibleJToggleButton This class implements accessibility support for


the JToggleButton class.

static class JToggleButton.ToggleButtonModel The ToggleButton model

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

Modifier and Method Description


Type

AccessibleContext getAccessibleContext() It gets the AccessibleContext associated with this


JToggleButton.
String getUIClassID() It returns a string that specifies the name of the l&f class that
renders this component.

protected String paramString() It returns a string representation of this JToggleButton.

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

Let's see the declaration for javax.swing.JCheckBox class.

1. public class JCheckBox extends JToggleButton implements Accessible


Commonly used Constructors:

Constructor Description

JJCheckBox() Creates an initially unselected check box button with no text, no icon.

JChechBox(String s) Creates an initially unselected check box with text.

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.

Java JCheckBox Example


1. import javax.swing.*;
2. public class CheckBoxExample
3. {
4. CheckBoxExample(){
5. JFrame f= new JFrame("CheckBox Example");
6. JCheckBox checkBox1 = new JCheckBox("C++");
7. checkBox1.setBounds(100,100, 50,50);
8. JCheckBox checkBox2 = new JCheckBox("Java", true);
9. checkBox2.setBounds(100,150, 50,50);
10. f.add(checkBox1);
11. f.add(checkBox2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }
16. public static void main(String args[])
17. {
18. new CheckBoxExample();
19. }}

Output:

Java JCheckBox Example with ItemListener


1. import javax.swing.*;
2. import java.awt.event.*;
3. public class CheckBoxExample
4. {
5. CheckBoxExample(){
6. JFrame f= new JFrame("CheckBox Example");
7. final JLabel label = new JLabel();
8. label.setHorizontalAlignment(JLabel.CENTER);
9. label.setSize(400,100);
10. JCheckBox checkbox1 = new JCheckBox("C++");
11. checkbox1.setBounds(150,100, 50,50);
12. JCheckBox checkbox2 = new JCheckBox("Java");
13. checkbox2.setBounds(150,150, 50,50);
14. f.add(checkbox1); f.add(checkbox2); f.add(label);
15. checkbox1.addItemListener(new ItemListener() {
16. public void itemStateChanged(ItemEvent e) {
17. label.setText("C++ Checkbox: "
18. + (e.getStateChange()==1?"checked":"unchecked"));
19. }
20. });
21. checkbox2.addItemListener(new ItemListener() {
22. public void itemStateChanged(ItemEvent e) {
23. label.setText("Java Checkbox: "
24. + (e.getStateChange()==1?"checked":"unchecked"));
25. }
26. });
27. f.setSize(400,400);
28. f.setLayout(null);
29. f.setVisible(true);
30. }
31. public static void main(String args[])
32. {
33. new CheckBoxExample();
34. }
35. }
Java JRadioButton

The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.

It should be added in ButtonGroup to select one radio button only.

JRadioButton class declaration

Let's see the declaration for javax.swing.JRadioButton class.

1. public class JRadioButton extends JToggleButton implements Accessible


Commonly used Constructors:

Constructor Description

JRadioButton() Creates an unselected radio button with no text.

JRadioButton(String s) Creates an unselected radio button with specified text.

JRadioButton(String s, boolean selected) Creates a radio button with the specified text and selected status.

Commonly used Methods:

Methods Description

void setText(String s) It is used to set specified text on button.

String getText() It is used to return the text of the button.


void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

Java JRadioButton Example


1. import javax.swing.*;
2. public class RadioButtonExample {
3. JFrame f;
4. RadioButtonExample(){
5. f=new JFrame();
6. JRadioButton r1=new JRadioButton("A) Male");
7. JRadioButton r2=new JRadioButton("B) Female");
8. r1.setBounds(75,50,100,30);
9. r2.setBounds(75,100,100,30);
10. ButtonGroup bg=new ButtonGroup();
11. bg.add(r1);bg.add(r2);
12. f.add(r1);f.add(r2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. public static void main(String[] args) {
18. new RadioButtonExample();
19. }
20. }
Output

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.

JTabbedPane class declaration

Let's see the declaration for javax.swing.JTabbedPane class.

1. public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingCon


stants
Commonly used Constructors:

Constructor Description

JTabbedPane() Creates an empty TabbedPane with a default tab placement of


JTabbedPane.Top.
JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified tab placement.

JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab placement and
tabLayoutPolicy) tab layout policy.

Java JTabbedPane Example


1. import javax.swing.*;
2. public class TabbedPaneExample {
3. JFrame f;
4. TabbedPaneExample(){
5. f=new JFrame();
6. JTextArea ta=new JTextArea(200,200);
7. JPanel p1=new JPanel();
8. p1.add(ta);
9. JPanel p2=new JPanel();
10. JPanel p3=new JPanel();
11. JTabbedPane tp=new JTabbedPane();
12. tp.setBounds(50,50,200,200);
13. tp.add("main",p1);
14. tp.add("visit",p2);
15. tp.add("help",p3);
16. f.add(tp);
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. public static void main(String[] args) {
22. new TabbedPaneExample();
23. }}
Output:

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

Modifier Method Description

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.

void setViewportView(Component) Set the scroll pane's client.

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.

JList class declaration

Let's see the declaration for javax.swing.JList class.

1. public class JList extends JComponent implements Scrollable, Accessible


Commonly used Constructors:

Constructor Description

JList() Creates a JList with an empty, read-only, model.

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

Void addListSelectionListener(ListSelectionListener It is used to add a listener to the list, to be notified eac


listener) time a change to the selection occurs.

int getSelectedIndex() It is used to return the smallest selected cell index.

ListModel getModel() It is used to return the data model that holds a list of
items displayed by the JList component.

void setListData(Object[] listData) It is used to create a read-only ListModel from an arra


of objects.

Java JList Example


1. import javax.swing.*;
2. public class ListExample
3. {
4. ListExample(){
5. JFrame f= new JFrame();
6. DefaultListModel<String> l1 = new DefaultListModel<>();
7. l1.addElement("Item1");
8. l1.addElement("Item2");
9. l1.addElement("Item3");
10. l1.addElement("Item4");
11. JList<String> list = new JList<>(l1);
12. list.setBounds(100,100, 75,75);
13. f.add(list);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new ListExample();
21. }}

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.

JComboBox class declaration

Let's see the declaration for javax.swing.JComboBox class.

1. public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, A


ctionListener, Accessible
Commonly used Constructors:

Constructor Description

JComboBox() Creates a JComboBox with a default data model.

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.

Commonly used Methods:

Methods Description

void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

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.

void addActionListener(ActionListener a) It is used to add the ActionListener.

void addItemListener(ItemListener i) It is used to add the ItemListener.

Java JComboBox Example


1. import javax.swing.*;
2. public class ComboBoxExample {
3. JFrame f;
4. ComboBoxExample(){
5. f=new JFrame("ComboBox Example");
6. String country[]={"India","Aus","U.S.A","England","Newzealand"};
7. JComboBox cb=new JComboBox(country);
8. cb.setBounds(50, 50,90,20);
9. f.add(cb);
10. f.setLayout(null);
11. f.setSize(400,500);
12. f.setVisible(true);
13. }
14. public static void main(String[] args) {
15. new ComboBoxExample();
16. }
17. }

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:

You might also like