0% found this document useful (0 votes)
20 views

ch3 Java

The document discusses AWT and Swing in Java. It explains that AWT provides basic GUI components like frames and buttons, while Swing builds upon AWT to provide more advanced, lightweight and platform-independent components. It then provides examples to demonstrate how to create simple GUI applications using both AWT and Swing components. Key components of each are also listed and briefly described.

Uploaded by

eyobeshete16
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

ch3 Java

The document discusses AWT and Swing in Java. It explains that AWT provides basic GUI components like frames and buttons, while Swing builds upon AWT to provide more advanced, lightweight and platform-independent components. It then provides examples to demonstrate how to create simple GUI applications using both AWT and Swing components. Key components of each are also listed and briefly described.

Uploaded by

eyobeshete16
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

CHAPTER THREE

AWT AND SWING


3.1. Concepts of AWT and Swing
3.1.1. AWT controls (Frames, Label, Button, text Field, Combo box ..)
3.1.2. Swing controls (JFrame, JLabel, JButton, JtextField, JComboBox,...)
3.2. Event Handling
3.2.1. Sources
3.2.2. Listeners
AWT and Swing in Java

AWT and Swing are used to develop window-based applications in Java. Awt is an abstract
window toolkit that provides various component classes like Label, Button, TextField, etc., to
show window components on the screen. All these classes are part of the Java.awt package.
On the other hand, Swing is the part of JFC (Java Foundation Classes) built on the top of AWT
and written entirely in Java. The javax.swing API provides all the component classes like
JButton, JTextField, JCheckbox, JMenu, etc.
The components of Swing are platform-independent, i.e., swing doesn't depend on the operating
system to show the components. Also, the Swing's components are lightweight.

Difference between AWT and Swing:

S.NO AWT Swing


1. Java AWT is an API to develop GUI Swing is a part of Java Foundation Classes
applications in Java and is used to create various applications.
2. The components of Java AWT are The components of Java Swing are light
heavy weighted. weighted.
3. Java AWT has comparatively less Java Swing has more functionality as
functionality as compared to Swing. compared to AWT.
4. The execution time of AWT is more The execution time of Swing is less than
than Swing. AWT.
5. The components of Java AWT are The components of Java Swing are platform
platform dependent. independent.
7. AWT provides comparatively less Swing provides more powerful components.
powerful components.
8 AWT components require java.awt Swing components requires javax.swing
package package
9 AWT is a thin layer of code on top of Swing is much larger swing also has very
the operating system. much richer functionality.
10 AWT stands for Abstract windows Swing is also called as JFC(java Foundation
toolkit . classes). It is part of oracle’s JFC.
11 Using AWT , you have to implement a Swing has them built in.
lot of things yourself .
Examples of swing

import javax.swing.*;
public class SwingApp {
SwingApp(){
JFrame f = new JFrame();
JLabel firstName = new JLabel("First Name");
firstName.setBounds(20, 50, 80, 20);
JLabel lastName = new JLabel("Last Name");
lastName.setBounds(20, 80, 80, 20);
JLabel dob = new JLabel("Date of Birth");
dob.setBounds(20, 110, 80, 20);
JTextField firstNameTF = new JTextField();
firstNameTF.setBounds(120, 50, 100, 20);
JTextField lastNameTF = new JTextField();
lastNameTF.setBounds(120, 80, 100, 20);
JTextField dobTF = new JTextField();
dobTF.setBounds(120, 110, 100, 20);
JButton sbmt = new JButton("Submit");
sbmt.setBounds(20, 160, 100, 30);
JButton reset = new JButton("Reset");
reset.setBounds(120,160,100,30);
f.add(firstName);
f.add(lastName);
f.add(dob);
f.add(firstNameTF);
f.add(lastNameTF);
f.add(dobTF);
f.add(sbmt);
f.add(reset);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
Output

Java awt Example


To understand the differences between Awt and Swing, we have created the same example in
awt as well. Consider the following example.
import java.awt.*;
public class AwtApp extends Frame {
AwtApp(){
Label firstName = new Label("First Name");
firstName.setBounds(20, 50, 80, 20);
Label lastName = new Label("Last Name");
lastName.setBounds(20, 80, 80, 20);
Label dob = new Label("Date of Birth");
dob.setBounds(20, 110, 80, 20);
TextField firstNameTF = new TextField();
firstNameTF.setBounds(120, 50, 100, 20);
TextField lastNameTF = new TextField();
lastNameTF.setBounds(120, 80, 100, 20);
TextField dobTF = new TextField();
dobTF.setBounds(120, 110, 100, 20);
Button sbmt = new Button("Submit");
sbmt.setBounds(20, 160, 100, 30);
Button reset = new Button("Reset");
reset.setBounds(120,160,100,30);
add(firstName);
add(lastName);
add(dob);
add(firstNameTF);
add(lastNameTF);
add(dobTF);
add(sbmt);
add(reset);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
AwtApp awt = new AwtApp();
}
Java AWT Controls

Java AWT controls are the controls that are used to design graphical user interfaces or web
applications. To make an effective GUI, Java provides java.awt package that supports various
AWT controls like Label, Button, CheckBox, CheckBox Group, List, Text Field, Text Area,
Choice, Canvas, Image, Scrollbar, Dialog, File Dialog, etc that creates or draw various
components on web and manage the GUI based application.
Structure of the Java AWT Controls
The structure of the AWT is quite simple and it is used extensively in programs. Every AWT
inherits controls from the Container Class.
Container Class
It represents objects in graphical representation and it is an abstract class in the GUI interface.
The following are the list of commonly used UI elements in the GUI or commonly known as
Graphical User Interface.

GUI is a Graphical Interface that visually represents communication presented to the user for
easy interaction with the machine. GUI means Graphical User Interface. The common user
Interface includes Graphical representations like buttons and icons, and communication can be
performed by interacting with these icons rather than the usual text-based or command-based
communication.

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.

The following are AWT controls

1. Label
A label is a user for placing text inside the container. A label is used only for inputting text. The
label does not imply that the text can be altered or it can be used as a button which can be further
worked upon.
Syntax:

2. Button
This command generates a button in the User Interface. Clicking on the button would move the
command to another page or another web server which is used to show several other outputs in
the user interface page.
Syntax:

3. Checkbox
There can be a certain question and the checkbox is used to determine the true or false nature of
the question being asked. If the checkbox is ticked then it means that the said question is true
which if it is unchecked it means that the said question is false. It is basically a true or false state
in Java programming language.
Syntax:

4. Checkbox Group
As the name implies the checkbox group is a set of checkboxes that are being used in the
programming language. There are many checkboxes that are being used and hence the group of
checkboxes is known as the checkbox group.
Syntax:

5. List
The list gives a scrolling list of items for the user. The scrolling list of items is also being set by
the user. The user sets the scrolling list of items such as Fruits, Vegetables, some questionnaire
or other facts.
Syntax:
6. Text Field
A text field is used for the editing of a particular line of text which can be used within the
programming concept.
Syntax:

7. Text Area
A text area is used for the editing of multiple lines of text. The only difference between the Text
field and Text area is that Text Field is used for editing a single line of text within the user
interface while a Text Area is used for editing multiple lines of text.
Syntax:

8. Choice
A choice, as the name implies, shows the various options and the choice that is selected is shown
in the top menu bar of the screen.
Syntax:

9. Canvas
In the canvas space, there can be an input being given by the user or the user can draw something
on the Canvas space being given.
Syntax:
10. Image
There can be a single image or multiple images within a UI. There can be a button being
associated with an image and when it is clicked it can produce some functionality.
Syntax:

11. Scroll Bar


The scroll bar like a normal one is used to scroll or move from a varied range of values. The user
selects one value from those range of values.
Syntax:

12. Dialog
The dialog is used to take some form of input from the user and produce it in a sequential
manner.
Syntax:

13. File Dialog


From a file dialog, a user can select a file which he/she wishes to use.
Syntax:
Components of Java Swing

Some of the important and common components of the Java Swing class are:

JFrame: JFrame is a top-level container that represents the main window of a GUI
application. It provides a title bar, and minimizes, maximizes, and closes buttons.
JPanel: JPanel is a container that can hold other components. It is commonly used to group
related components together.
JButton: JButton is a component that represents a clickable button. It is commonly used to
trigger actions in a GUI application.
JLabel: JLabel is a component that displays text or an image. It is commonly used to provide
information or to label other components.
JTextField: JTextField is a component that allows the user to input text. It is commonly used
to get input from the user, such as a name or an address.
JCheckBox: JCheckBox is a component that represents a checkbox. It is commonly used to
get a binary input from the user, such as whether or not to enable a feature.
JList: JList is a component that represents a list of elements. It is typically used to display a
list of options from which the user can select one or more items.
JTable: JTable is a component that represents a data table. It is typically used to present data
in a tabular fashion, such as a list of products or a list of orders.
JScrollPane: JScrollPane is a component that provides scrolling functionality to other
components. It is commonly used to add scrolling to a panel or a table.

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.

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,
horizontalAlignment) and 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 It sets the alignment of the label's contents along the
alignment) 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.

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 Creates a new TextField initialized with the specified text and
columns) columns.
JTextField(int columns) Creates a new empty TextField with the specified number of
columns.

Commonly used Methods:


Methods Description
void addActionListener(ActionListener It is used to add the specified action listener to
l) receive action events 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
removeActionListener(ActionListener l) that it no longer receives action events from this
textfield.

Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits JTextComponent class
JTextArea class declaration
Let's see the declaration for javax.swing.JTextArea class.
public class JTextArea extends JTextComponent
Commonly used Constructors:
Constructor Description
JTextArea() Creates a text area that displays no text initially.
JTextArea(String s) Creates a text area that displays specified text initially.
JTextArea(int row, int column) Creates a text area with the specified number of rows and
columns that displays no text initially.
JTextArea(String s, int row, int Creates a text area with the specified number of rows and
column) columns that displays specified text.

Commonly used Methods:


Methods Description
void setRows(int rows) It is used to set specified number of rows.
void setColumns(int cols) It is used to set specified number of columns.
void setFont(Font f) It is used to set the specified font.
void insert(String s, int position) It is used to insert the specified text on the specified position.
void append(String s) It is used to append the given text to the end of the document.

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.

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
selected) it is initially selected.
JCheckBox(Action a) Creates a check box where properties are taken from the
Action supplied.

Commonly used Methods:


Methods Description
AccessibleContext It is used to get the AccessibleContext associated with
getAccessibleContext() this JCheckBox.
protected String paramString() It returns a string representation of this JCheckBox.

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.

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 Creates a radio button with the specified text and
selected) 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 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.


public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, Act
ionListener, 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<?> Creates a JComboBox that contains the elements in the specified
items) Vector.

Commonly used Methods:


Methods Description
void addItem(Object anObject) It is usedto add an item to the item list.
void removeItem(Object anObject) It is usedto delete an item to the item list.
void removeAllItems() It is usedto remove all the items from the list.
void setEditable(boolean b) It is usedto determine whether the JComboBox is
editable.
void addActionListener(ActionListener It is used to add the ActionListener.
a)
void addItemListener(ItemListener i) It is used to add the ItemListener.

Java JTable

The JTable class is used to display data in tabular form. It is composed of rows and columns.

JTable class declaration

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


Commonly used Constructors:
Constructor Description
JTable() Creates a table with empty cells.
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.

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> Creates a JList that displays elements from the specified, non-
dataModel) null, model.

Commonly used Methods:


Methods Description
Void It is used to add a listener to the list, to be
addListSelectionListener(ListSelectionListener notified each time a change to the
listener) 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 array of objects.

Java JFrame

The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class.
JFrame works like the main window where components like labels, buttons, textfields are added
to create a GUI.

Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.

Nested Class
Modifier and Class Description
Type
protected class JFrame.AccessibleJFrame This class implements accessibility support for
the JFrame class.

Fields
Modifier and Type Field Description
protected accessibleContext The accessible context property.
AccessibleContext
static int EXIT_ON_CLOSE The exit application default window close
operation.
protected JRootPane rootPane The JRootPane instance that manages the
contentPane and optional menuBar for this
frame, as well as the glassPane.
protected Boolean rootPaneCheckingEnabled If true then calls to add and setLayout will
be forwarded to the contentPane.
Constructors
Constructor Description
JFrame() It constructs a new frame that is initially invisible.
JFrame(GraphicsConfiguration gc) It creates a Frame in the specified
GraphicsConfiguration of a screen device and a blank
title.
JFrame(String title) It creates a new, initially invisible Frame with the
specified title.
JFrame(String title, It creates a JFrame with the specified title and the
GraphicsConfiguration gc) specified GraphicsConfiguration of a screen device.

Useful Methods
Modifier and Method Description
Type
protected void addImpl(Component comp, Object Adds the specified child
constraints, int index) Component.
protected createRootPane() Called by the constructor
JRootPane methods to create the default
rootPane.
protected void frameInit() Called by the constructors to
init the JFrame properly.
Void setContentPane(Containe contentPane) It sets the contentPane
property
static void setDefaultLookAndFeelDecorated(boolean Provides a hint as to whether
defaultLookAndFeelDecorated) or not newly created JFrames
should have their Window
decorations (such as borders,
widgets to close the window,
title...) provided by the
current look and feel.
void setIconImage(Image image) It sets the image to be
displayed as the icon for this
window.
void setJMenuBar(JMenuBar menubar) It sets the menubar for this
frame.
void setLayeredPane(JLayeredPane layeredPane) It sets the layeredPane
property.
JRootPane getRootPane() It returns the rootPane object
for this frame.
TransferHandler getTransferHandler() It gets the transferHandler
property.

Event and Listener (Java Event Handling)

Changing the state of an object is known as an event. For example, click on button, dragging
mouse etc. The java.awt.event package provides many event classes and Listener interfaces for
event handling.

Steps to perform Event Handling

Following steps are required to perform event handling:

Register the component with the Listener


Registration Methods

For registering the component with the Listener, many classes provide the registration methods. For
example:

Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}

You might also like