0% found this document useful (0 votes)
10 views36 pages

Introduction To Programming

This document provides an introduction to programming and Java. It discusses what a program is, what programming is, and common programming languages. It then defines Java as an object-oriented programming language initially created by James Gosling in 1991. The document outlines Java's history and describes its advantages such as being simple, secure, portable, and able to run on any platform. It also discusses the Java Virtual Machine (JVM), how Java code is compiled and run, and integrated development environments (IDEs) for rapid application development in Java.

Uploaded by

ayushdwivedy73
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
10 views36 pages

Introduction To Programming

This document provides an introduction to programming and Java. It discusses what a program is, what programming is, and common programming languages. It then defines Java as an object-oriented programming language initially created by James Gosling in 1991. The document outlines Java's history and describes its advantages such as being simple, secure, portable, and able to run on any platform. It also discusses the Java Virtual Machine (JVM), how Java code is compiled and run, and integrated development environments (IDEs) for rapid application development in Java.

Uploaded by

ayushdwivedy73
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 36

INTRODUCTION TO PROGRAMMING

What is program?
• A set of such structured instructions is called a Program which
tells the computer what to do.
• The process of writing specific instruction in a computer language
is called programming.
• Person who writes such programs is known as a programmer or
coder.
• The language used in a computer program is called as
Programming Language.
Ex: BASIC, FORTRAN, Pascal, COBOL, C, C++ and JAVA etc.
What is java?
• Java (originally known as oak) is a computer programming
language (which is also a high-level language).
• Its is similarity to ordinary English language) has a set of rules that
determine how the instructions are to be written. These rules are
known as its syntax.
History of Java
• James Gosling (a Canadian Computer Scientist, Born 19th May 1955)
initiated the Java language project in June 1991 for use in one of his
many set- top box projects.
• The language, initially called Oak after an oak tree that stood outside
Gosling‘s office, also went by the name Green and ended up later being
renamed as Java, from a list of random words.
• Sun released the first public implementation as Java 1.0 in 1995. It is a
Write Once, Run Anywhere(WORA) type language, providing no-cost
run- times on popular platforms.
• On 13 November 2006, Sun released much of Java as free and open
source software under the terms of the GNU (GNU is an operating system
which is completely free software system) General Public License
(GPL).On 8 May 2007, Sun finished the process, making all of Java‘s
core code free and open-source, aside from a small portion of code to
which Sun did not hold the copyright.
Advantages / Characteristics of java :
• Simple :
➢ Java is Easy to write and more readable.
➢ Java has a concise, cohesive set of features that makes it
easy to learn and use.
➢ Most of the concepts are drawn from C++, thus making
Java learning simpler.
• Secure :
➢ Java program cannot harm other system thus making it
secure.
➢ Java provides a secure means of creating Internet
applications.
➢ Java provides secure way to access web applications.
• Portable :
➢ Java programs can execute in any environment for which
there is a Java run-time system.
➢ Java programs can run on any platform (Linux, Window,
Mac)
➢ Java programs can be transferred over world wide web (e.g
applets)
• Object-oriented :
➢ Java programming is object-oriented programming
language.
➢ Like C++, java provides most of the object oriented
features.
➢ Java is pure OOP Language. (while C++ is semi object
oriented)
• Platform independent:
➢ Languages can be platform dependent or independent.
➢ But Java is a Platform independent which is portable &
easily executed on all operating systems (windows, Linux,
solaris) or Java programs can run on any platform.

• Robust :
➢ Java encourages error-free programming by being strictly
typed and performing runtime checks.
• Multithreaded :
➢ Java provides integrated support for multithreaded
programming.
• Architecture-neutral :
➢ Java is not tied to a specific machine or operating system
architecture.
➢ Java is machine independent.

• Interpreted :
➢ Java supports cross-platform code through the use of Java
bytecode.
➢ Bytecode can be interpreted on any platform by JVM (Java
Virtual Machine).
• High performance :
➢ Bytecodes are highly optimized.
➢ JVM can execute bytecodes much faster .
• Distributed :
➢ Java is designed with the distributed environment.
➢ Java can be transmitted over internet.
• Dynamic :
➢ Java programs carry substantial amounts of run-time type
information with them that is used to verify and resolve
accesses to objects at run time.
What JVM and its work:
• JVM(Java Virtual Machine) acts as a run-time engine to run Java
applications.
• JVM is the one that actually calls the main method present in a
Java code.
• JVM is a part of JRE(Java Runtime Environment).
• Java applications are called WORA (Write Once Run Anywhere).
This means a programmer can develop Java code on one system
and can expect it to run on any other Java-enabled system without
any adjustment. This is all possible because of JVM.
• When we compile a .java file, .class files(contains byte-code)
with the same class names present in .java file are generated by the
Java compiler.
• This .class file goes into various steps when we run it. These steps
together describe the whole JVM.
Source Code :
• The core program or text written in any computer language
(like C, C++, Java, etc.) is called source code.
• Usually it is a collection of computer instructions written by
using any human readable computer language.
• Source code files have the extension class.
Object Code:
• The program in the form of machine instructions or binary instructions
(i.e., in computer readable form).
• It is generally produced by compiler/interpreter, but in case of Java, it is
produced by JVM.
Byte Code:
• In Java, when a source code is compiled, it doesn‘t directly convert into
object code, rather it converts into what, is known as byte code.
• So, a byte code is machine instruction that the Java compiler (Javac)
generates.
Note :
❖ Javac –compiler that converts source code to byte code.
❖ JVM- interpreter that converts byte code to machine language code.
❖ Source Code (program.java) Æ compile Æ Byte Code (program. class).
❖ Byte Code (program. class) Æ JVM Æ Machine Code.
RAPID APPLICATION DEVELOPMENT (RAD) USING IDE:
• Rapid application development is abbreviated as RAD.
• It is an object- oriented approach for software development, being
introduced by James Martin in the 1980s.
• It includes a method of development as well as software tools
commonly known as ICU. where,
i. I-Iterative development.
ii. C-Construction of prototypes.
iii. U-Use of Computer-Aided Software Engineering (CASE) tools.
• RAD includes analyzing, designing, building and testing phases the form
of short iterative cycle which has a number of rare advantages over the
traditional sequential development methods.
• Rapid application development is a response of different Processes
developed in the 1970s and 1980s, such as the Structured Systems
Analysis and Design Method and other Waterfall Model.
• Following are two most popular RAD systems;
i. NetBeans IDE is a cross-platform RAD tool for creating visual
desktop, mobile and web applications for Linux, Windows and
Mac OS X.
ii. MyEclipse is a RAD environment, focusing on enterprise Java and
web application development.
Advantages of RAD are:
✓ Increased speed of software development via including rapid prototyping,
virtualization of system related routines, the use of CASE tools, and other
techniques.
✓ Reduced complexity of development.
✓ More focus on simplicity and usability of GUI components.
Java Development Kit (JDK):
• Java programs are of mainly two types-applets and applications.
• Applets are the Java programs executed by a web browser while
applications are the programs that execute directly on your machine.
• JDK is a program development environment for writing Java applets and
applications.
• Sun decided to give away a Java Development Kit (JDK) that would
provide basic tools needed for Java programming.
• JDK provides all the tools needed to write powerful Java applications or
applets. JDK includes JRE (Java Runtime Environment) and some other
basic tools, like an interpreter/loader (Java), a compiler (javac), an
archiever (jar), a documentation generator (javadoc), etc.
These tools are described below:
i. JRE (Java Runtime Environment): It is the environment which is used
to run the predeveloped applets or applications in JDK.
ii. Javac: Java compiler is named as Javac. The Javac takes input source
code and converts them into compiled byte code.
iii. Java: The Java interpreter/loader, normally called as Java. It can be
used to execute Java applications. The interpreter translates byte code
directly into program actions.
iv. Java doc : It is used to generate our source code into HTML files
documentation.
v. Jar: It is an archiever used to create jar files. A JAR file is a file that
contains the class, image and sound files for a Java application or applet
gathered into a single file and possibly compressed.
vi. Applet Viewer: This small program provides a real Java environment
for testing applets. It loads the HTML files (in which the applet has been
embedded) and displays the application in a browser like window.
Integrated Development Environment (IDE):
• An Integrated Development Environment is abbreviated as IDE.
• It is a software tool which provides a way to create and debug programs
easily.
• IDEs are designed to maximize programmer productivity by providing
developing of components with similar user interfaces.
• An IDE brings all of the programming tools into one convenient place.
• There was a time when programmers had to edit files, save them, run the
compiler and linker, build the application and then run it through a
debugger and all these works were done separately. IDEs overcome this
problem.
• Today, IDEs bring editor, compiler, linker and debugger into one place
along with project management tools to increase programmer
productivity.
• In other words, IDE is a software program that is designed to help
programmers and developers to build software.
• One of the most important features of an IDE tool is that the program
code can be continuously parsed while it is being edited and provides
instant feedback when syntax errors are occurred.
Most IDEs include :
1. A source code editor, similar to an HTML text editor. It is where
programmers write the source code for their programs.
2. A compiler which converts the source code into intermediate code
(Byte code) and an interpreter (JVM) to execute that compiler
generated byte code.
3. Build automation tools help to automate the processes that need to
happen with most software development like compiling debugging
and deployment.
4. A debugger helps to point out the exact spot where there is a
problem in the source code.
5. A Graphical User Interface (GUI) builder simplifies the creation
of GUIs.
NetBeans IDE:
• NetBeans IDE is a free, open source, integrated development
environment (IDE) that enables you to develop desktop, mobile and web
applications.
• The IDE supports application development in various languages,
including Java, HTML5, PHP and C++.
• The IDE provides integrated support for the complete development cycle,
from project creation through debugging, profiling and deployment.
• The IDE runs on Windows, Linux, Mac OS X, and other UNIX- based
systems.
• The IDE provides comprehensive support for JDK technologies and the
most recent Java enhancements.
• It is the first IDE that provides support for JDK 8, Java EE 7, and JavaFX
2. The IDE fully supports Java EE using the latest standards for Java,
XML, Web services, and SQL and fully supports the Glassfish Server, the
reference implementation of Java EE.
• NetBeans IDE 8.1 is a free and open-source Java Integrated Development
Environment. It is the first free IDE providing support for JDK 8
previews, JDK7, Java EE 7 including its related HTML5 enhancements
and JavaFX 2.
• NetBeans IDE incorporates many tools to facilitate creating, managing
and running a program, includingfeatures like a Graphical User Interface
(GUI)fordevelopment, a fancy text editor, an output window, links
forcompilation errors, buttons to compile and run the program,a debugger
and many more.
Integrated modules of a NetBeans IDE are :
1. NetBeans Profiler:
➢ It is a tool for the monitoring of Java applications.
➢ It helps developers to find memory leaks and optimize
speed.
❖ GUI Design Tool :
It enables developers to prototype and design Swing
GUI by dragging and positioning graphical components.
❖ NetBeans JavaScript Editor:
The NetBeans JavaScript editor provides
extendedsupport for JavaScript, Ajax, and CSS.
Some advantages of NetBeans IDE are :
a. Best support for latest advanced Java technology.
b. Fast and smart code editing.
c. Easy and efficient project management.
d. Supports rapid applicationdevelopment mechanism.
e. Enable users to write bug free code.
2. Java Editors:
To write your Java programs, you will need a text editor. There
are even more sophisticated IDEs available in the market. But for
now, you can consider one of the following:
❖ Notepad: On Windows machine you can use any simple
text editor like Notepad (Recommended for this tutorial),
Text Pad.
❖ NetBeans: is a Java IDE that is open-source and free
which can be downloaded from
http://www.netbeans.org/index.html.
❖ Eclipse: is also a Java IDE developed by the eclipse
open-source community and can be downloaded from
http://www.eclipse.org/.

FAMILIARIZATION OF IDE USING BASIC INTERFACE COMPONENTS:


NetBeans IDE provides a way to interact with the different components
of JAVA through visual graphical elements (Pictures, icons, symbols, etc.). To
start NetBeans IDE follow the steps:-
Step1: Click Start Button Æ All programs Æ NetBeans IDE 8.1
Or
Double click on the shortcut icon of NetBeans IDE 8.1 on the Desktop.
Step 2: The loading screen of NetBeans IDE 8.1 will appear on your desktop.

Loading screen of Netbeans IDE 8.1


Step 3: After loading , the welcome screen of NetBeans IDE 8.1 will appear.
Different parts of IDE windows:

The Net Beans IDE contains various controls and menus via which, a user can
easily interact and work according to their requirements.
1. Title Bar: It displays the name of the application or a program.
2. Menu Bar: It provides the various commands used to work with
Net Beans IDE, such as file, edit, view, etc.
3. Tool Bar: It provides a way to quickly access the commonly used
commands.
4. Palette Window: This window contains all the containers and
other graphical components such as labels, panels, text fields etc.
5. Projects Window: This window shows a logical structure of
different project contents.
6. Inspector Window: This window displays a hierarchical tree
structure of all the components used in the current form.
7. Properties Window: This window displays the editable properties
of the currently selected graphical component.
8. Design Area: It is the primary area used for creating and editing of
Java forms.
9. Source Editor:Itis a fully featured text editor program which
includes a compiler, debugger and other components of IDE.
10. Output Window: This window shows the output messages from
the Net Beans IDE. Output window automatically shows the
messages after compilation of a program.
GETTING FAMILIAR WITH JAVA SWING USER INTERFACE
COMPONENTS :
Components & Container:
• In Java, JFC (Java Foundation Classes) support GUI features.
• JFCs are pre-written code in the form of class libraries (coded routines)
that give the programmer a comprehensive set of GUI routines to use.
• JFC is an extension of the original Java Abstract Window Toolkit
(AWT).
Graphical User Interface (GUI) :
• It is a type of user computer interface that allows users to take advantages
of computer graphical capabilities to make program easier.
• A GUI is developed with the help of graphical elements such as buttons,
scroll bars, list and text fields.
• These elements are called components of GUI Java GUI programming
involves two packages, the original abstract windows kit and newer
swing toolkit.
• Components present in AWT are all present in swing. Swing components
have the prefix J to differ them from AWT. For example, JLabel instead
of Label.
Java Swing:
• Java Swing is a group of classes that provides more powerful and
flexible GUI (Graphical User Interface) components than does the AWT
(Abstract Window Toolkit).
• Swing is built on the foundation of AWT and concentrate to the
limitations present in the AWT.
• The two key features of swing are— light weightcomponents and a
pluggable look and feel.
• Together they provide an elegant, yet easy to use solution to the
problems occurred in AWT.
Components in Swing:
• A component is an independent visual control, such as a push button or
slider.
• Swing components are derived from the JComponent class.
• For example, JComponent supports the Pluggable Look And Feel
(PLAF), which means that each swing component is provided by java
rather than by native peers.
• The look and feel of a component is under the control of swing.
• JComponent inherits the two AWT classes; Container and Component,
to give GUI data item a better look. There are two types of graphical
components available in java swing :
(i) Container Control It is the control that holds some other swing
controls. For example, Panel, Frame etc.
(ii) Child Control Those controls which are available in the container
control are known as child control. For example, Button, List etc.
Some Basic Component of Swing :
• Swing components are represented by a class within the package
javax.swing.
• This package must be imported into every swing program. The package
javax.swing contains several classes that implements the basic GUI swing
components shown in the table below :

• The components given the table provide an easy way to create graphical
inbuilt software programs.Few of them are described below with their
properties and methods.
1) Label: Label is the display area for a short text string or an
image. It is created through JLabel component.It is easy to
use component which does not react on the input actions
performed by an user. A label displays a single line of read
only text. The text can be changed by the application, but a
common user cannot edit it directly.
Constructor:
❖ A java constructor has the same name as the name of the class to which
it belongs.
❖ Constructor‘s syntax does not include a return type, since constructors
never return a value.
❖ It is executed when we create new object of that class. JLabel provides
following constructors
JLabel (Icon i)
JLabel (String str)
JLabel (String str, Icon i, int align)
❖ Here, str and i are the text and icon respectively used for the label.
❖ The align argument specifies the horizontal alignment of the data item
within the dimensions of the label It must be one of the following values
LEFT, RIGHT, CENTER, TOP and DOWN.
Properties:
a. Background :This property is used to set the background colour of a
label. The colour of the label is displayed when opaque property is set to
true. The default setting value is false.
b. Enabled :This property is used to set whether the label is active or not at
run a. time.
c. Font :This property is used to set a font style for the text displayed on the
label.
d. Foreground :This property is used to set the foreground colour to be
displayed on the label. The foreground colour of the label is displayed
when opopaque property is set to be true but the default setting value is
false.
e. Text :This property is used to specify the text to be displayed on the label.
Methods :
a. voidsetText(String) :This method is used to set the text which will be
displayed with the label.
For example,<label_name>.setText(“Name”); It would set the
“Name” text on the specified label.
b. String getText() :This method is used to fetch the text displayed on the
label. For example,String str = <label_name>.getText();
It returns the text value available on the specified label.
2) Text Field Text Field is the simplest text component which
allows a user to feed input text at the run-time. It is derived
from JTextField component, which provides the basic
functionality common to swing components.JTextField
allows you to edit one line of text. If you enter numeric data
then you must have to convert it into text format because
numeric data could not be displayed in a textfield.

❖ JTextField provides following constructors


JTextField (int cols)
JTextField (String str, int cols)
JTextField (String str).
❖ Here, str is the string to be initially presented and cols is the number of
columns available in the textfield.
❖ If no string is specified, the textfield is initially empty.
❖ If the number of columns are not specified, it set as a specified strings
length.
Properties:
a. Background : This property is used to set the background colour of the
textfield.
b. Editable : This property is used to edit the contents of the textfield. If it is
set to true then the text available in the text field can be edited by the
user at run-time.
c. Enabled : It is used to set the textfield as activated or deactivated.
d. Font : This property is used to set a font style for the text to be displayed
in the textfield.
e. Foreground : This property is used to set the foreground colour of the
text to be displayed in the textfield.
f. Text : This property is used to specify the text to be displayed in the
textfield.
Methods:
1. voidsetText(String) This method is used to set the text displayed
by the text field.
For example, <textfield_name>.setText(“ Name”);
It would set the “Name” text in the specified textfield.
2. String getText() This method is used to fetch the text displayed in
a textfield.
For example, String str = <textfield_name>.getText( )
3. isEditable() This method returns the current state of the textfield.
If its value is true then the user can edit the text available in the
specified textfield.
4. isEnabled() It indicates whether the textfield is in activated state or
deactivated state.
3) Text Area: Text Area is a multi-line text component which
enables a user to enter a large amount of text. It is created
through JTextArea component class.

JTextArea provides these following constructors


JTextArea()
JTextArea(int numLines, int numChars)
JTextArea(string str).
Here, numLines specifies the height of the textarea, andnumChars
specifies its width, in characters. Initial text can be specified by str.
Properties:
a. Background : This property is used to set the background colour of the
textarea.
b. Foreground : The property is used to the set foreground colour of the text
available in the textarea.
c. Enabled : This property is used to set the textarea as enabled.
d. Editable Sets whether the textarea is editable or not. Default state/ value
is true.
METHODS:
a. String getText() This method is used to fetch the text displayed by the
textarea. For example, String str=<textarea_name>.getText();
b. voidsetText(String) This method is used to set the text which will be
displayed in the textarea.
For example, <textarea_name>.setText(“Name”);
It would set the “Name” text in the specified and textarea.
4) Button: A button is created through JButton class. JButton
class provides the functionality of a push button (or simply
say button). It allows an icon, string or both to be associated
with the push button.
JButton provides following constructors:
JButton(Icon i)
JButton(String str)
JButton(String str, Icon i)
Here, str and i are the string and icon used for the
button.
Properties:
a. Background This property is used to set the background colour of the
button. The colour of the button is displayed when it is set to be true.
b. Enabled This property is used to set whether the button is active or not at
the run-time.
c. Font This property is used to set font style of the text displayed on the
button.
d. Foreground This property is used to set the colour of the text displayed on
the button.
e. Text This property is used to set the text specified on the button.
f. Label Used to set the label of the button.
Methods:
a. voidsetText(String) This method is used to set the text which will be
displayed on the button.
For example, <button_name>.setText(“Push Button”);
It would set the “Push Button” text on the specified button.
b. String getText() This method is used to fetch the text displayed on the
button.
For example, String str = <button_name>.getText();
5) Check Box A check box is a graphical component that can
be in one of the state as ‗Selected‘ or ‗Deselected‘.It is
created through JCheckBox class. JCheckBox is a labeled
toggle switch whose super class is JToggleButton. Each time
when the user clicks it, its state changes. A check box
generates one item event and one action event per click.
o CheckBox1 Æ If checked, value = true/on.
o CheckBox3 Æ If unchecked, value = false/off.

JCheckBoxprovides following constructors:


JCheckBox(String str)
JCheckBox(String str, boolean selected).
The first constructor creates a checkbox that has
the text specified by str as a label and the second
constructor provides a way to prepare a
selectedcheckbox.
Properties:
a. Button Group Used to set a group of buttons in which the current control
belongs.
b. Font This property is used to set the font which will be displayed with
the checkbox.
c. Foreground This property is used to specify the font colour of the
checkbox.
d. Label Used to set the checkbox label by replacing setText(String)
method.
e. Selected This option is used to set the current value of a checkbox. If it is
set to true, it is displayed as checked otherwise unchecked.
f. Text This property is used to set the text to be displayed with the
checkbox.
Methods:
a. voidsetText(String Str) This method is used to set the text which will be
displayed with the check box.
For example,<Checkbox_name>.setText(“New CheckBox”);
It would set the “New CheckBox” text with the current checkbox.
b. String getText( ) This method is used to fetch the text displayed with the
checkbox.
For example,String str=<Checkbox_name>.getText();
c. boolean isSelected( ) This method returns the current state of the
checkbox. If it is checked, returns true otherwise false or unchecked.
d. void setSelected(Boolean b) This method is used to set the current state
of the checkbox.
6) Radio Button : Radio button is a group of mutually exclusive
buttons, in which only one button can be selected at a time.It
is supported by the JRadioButton class, which extends
JToggleButton. JRadioButton provides following
constructors :
JRadioButton(String str)
Here, str is the label of the button.
Properties:
a. Background: This property is used to set the background colour of the
radio button. The colour of the radio button is displayed when it is set to
be true.
b. Button Group: This property is used to set a name of the group of radio
buttons, to which the current radio button belongs.
c. Enabled :This property is used to set whether the radio button is active or
not at runtime.
d. Font: This property is used to set the font style of the text to be displayed
with the radio button.
e. Foreground :This property is used to set the font colour of the text
displayed with the radio button.
f. Label: This property is used to set the text displayed with any other
control.
g. Selected: This property is used to set the current state of the radio button.
If it is set to ture, it is displayed as checked otherwise unchecked.
h. Text: This property is used to set the text to be displayed with the radio
button.
Methods:
a. voidsetText(boolean b) This method is used to set the text, which will be
displayed with the radio button.
For example,<radiobutton_name>.setText(“New”);
It would set the “New”‘ text with the current radio button.
b. String getText() This method is used to fetch the text displayed with the
radio button.
For example, String str=<radiobutton_name>.getText()
c. boolean isSelected() This method returns the current state of the radio
button. If it is selected, it returns true otherwise false.
d. void setSelected(boolean b) This method sets current state of the radio
button for selection process.
7) Frame: It is a top-level container to which components are
added. It provides a home for the other components of the
interface, and dictates the overall feel of the application. A
frame is created through JFrame component and JFrame is a
subclass of java.awt. Frame and therefore, it inherits all the
features of an AWT frame. Frame has decorations such as a
border, a title, and supports button components that close or
iconify the window. Applications with GUI usually include
at least one frame.
JFrame provides the following constructors :
JFrame() Constructs a new frame that is initially invisible.
JFrame (string str) Constructs a new initially invisible frame
with the specified title.
Properties:
a. Background: This property is used to set the background colour of the
frame.
b. Title: This property is used to set the title of the frame.
c. DefaultCloseOperation: This property is set to hide-on-close, a value
taken from windows constants. This indicates that closing a JFrame
window results in setting the frame invisible.
Methods:
a) intgetDefaultCloseOperation() Returns the operation that occurs when the
user initiates a ‘close’ on this frame.
b) Void setDefaultCloseOperation() Sets the operation that will happen by
default when the user initiates a ‘close’ on this frame.
c) stringgetTitleGets the title of the frame.
d) voidsetTitle(String) Sets the title for this frame to the specified title.
8) Dialog Box : A dialog box is a small separate sub-window
that appears on the screen for providing/requesting
information to/from the users. According to the Java
documentation, a dialog window is an independent sub-
window meant to carry temporary notice apart from the main
swing application window. In Java language, the dialog box
is supported by the Java Swing control. It supports the
following types of controls.
❖ JDialog The JDialog is a Swing window dialog
which provides the normal behaviour of a window. It
displays a dialog box which has minimize, maximize
and close icons in the title bar of the dialog box. Most
dialogs present an error message or warning to a user,
but dialogs can present images, directory trees, or just
about anything compatible with the main swing
application that manages them.
❖ JOptionPane In Java language, the JOptionPane is
used to create a pp-up window with varied contents. It
can display an alert message box or an input box.
JOptionPane contains classes used for a Graphical
User Interface (GUI) that facilitates data entry and
data output. This class contains methods to display a
dialog box.
Swing JOptionPane allows you to :
✓ Create a dialog box
✓ Display information
✓ Request information
✓ Give the user a choice with buttons.
Structure of JoptionPane:
The basic elements of JOptionPane are as follows:
i. Icon : The icon determines the type of dialog box or message box.
There are four default options available. These are error,
information, warning and question.
ii. Message : The message option is used to set the text information
that we want to convey through the dialog box.
iii. Input Area : The input area allows the user to provide a response in
the form of an input. For user response, we can use JTextField,
JComboBox or JList.
iv. Button : The button area displays a set of buttons such as
OK/Cancel, Yes/No etc. The buttons can be customized according
to the user‘s requirements.
Dialog Type:
We can create four types of predefined dialog boxes. These are as
follows:
i. Input Dialog: This type of dialog box is used to enter the data. We can
use JTextField, JComboBox or JList for taking input. There are two
buttons; OK and Cancel.To create an input dialog box the
showInputDialog() method is used.
ii. Confirm Dialog:This type of dialog box is used to ask from the user about
the confirmation of any information. It includes buttons Yes/ No, OK and
Cancel etc. To create a confirm dialog box, the showConfirmDialog()
method is used.
iii. Message Dialog: The message dialog box is used to simply display some
information to the user. It includes only a single OK button. To create a
message dialog box, the showMessageDialog() method is used.
iv. Option Dialog: The option dialog is a flexible type dialog box. It can be
used to create a dialog box according to the user‘s need.
To create an option dialog box, the showOptionDialog() method is
used.
Message Type:
The icon of the JOptionPane is specified through the message type
values. Following table shows the possible values.
Option Type:
In Java language, the showConfirmDialog() and showOptionDialog()
methods are used to show the confirm dialog box and option dialog box
respectively, have choice to select which buttons will be displayed in the dialog
box. This could be done through the ‗option type‘ in the properties window.

Alternative Method for Creating JOptionPane :


We can create the JOptionPane also through coding. For this purpose, we
have to follow these steps:
i. First we have to specify the import command to import the javax.swing
API in the application as per following syntax importjavax.swing.*:
or
we can add following command to include the JOptionPane directly
importjavax.swing.JOptionPane;
ii. Then, we have to determine whether the dialog box is to be used as
message box, confirmation box, option box or input box and accordingly,
we have to use any of the following methods.
a) voidshowMessageDialog() Displays a message and waits until the
user acknowledges it by clicking Ok.
b) voidshowConfirmDialog() Displays a message and waits for user
response through button selection.
c) voidshowOptionDialog() Displays a message and waits for user
response from a group of options.
d) voidshowInputDialog() Displays a message and waits for input
from the user.
iii. Then, we need to specify the parent frame name.
iv. Then, we have to type the message which is to be displayed within the
dialog box.
v. For selecting the icon to be displayed, we need to specify the IDE code.
vi. Then, we have to select a set, for the types of buttons to be displayed
within the dialog box.
Note:
Step (ii) to (vi) can be done simultaneously in following statement
JOptionPane.showMessage(null, ―Message to be displayed‖, dialog);
9) Panel:
It is a lightweight container used for holding
components which include JButton, JLabel, JList, etc.
A panel is created through JPanel component.They are
used to let the developer have more control over
positioning and style of widgets on the screen and to
give a better structure to the code. JPanels are
fundamental in the creation of a professional GUI.
JPanel provides the following constructors.
✓ JPanel() Creates a new panel with a double
buffer and a flow layout.
✓ JPanel(boolean) Creates a new panel with flow
layout and the specified buffering strategy.
✓ J Panel (LayoutManager) Creates a view
buffered panel with the specified layout
manager.
✓ JPanel(LayoutManager, boolean) Creates a new
panel with the specified layout manager and
buffering strategy.
Methods:
i. String paramstring() Returns a string representation of this panel.
ii. AccessibleContextgetAccessibleContext() Gets the accessiblecontext
associated with this JPanel.
iii. voidadd(Component) Adds the specified component to the panel.
iv. intgetComponentCount() Gets the number of components in this panel.
v. void remove(Component) Removes the specified component.
10) Scroll Pane: A scroll pane is created through
JScrollPanecomponent. It provides a scrollable view of a
component. When screen real state is limited, use a scroll
pane to display a component that is large or one whose size
can change dynamically.
Scroll pane provides a way of scrolling horizontally and vertically if the widget
becomes any bigger than the viewport size.JScrollPane is used primarily in
JTextArea, JList, and JTable where the data displayed by the widget is changed
dynamically and can really affect the size and dimension of the widget.
✓ JScrollPane provides the following constructors
✓ JscrollPane() Creates an empty (no viewport view)
✓ JScrollPanewhere both horizontal and vertical
scrollbars appear when needed.
✓ JScrollPane(Component view) Creates a JscrollPane
that displays the contents of the specified component,
where both horizontal and vertical scrollbars appear
whenever the component‘s contents are larger than the
view.
✓ JScrollPane(Component view, int vsbPolicy, int
hsbPolicy) Creates a JscrollPane that displays the
view component in a viewport whose view position
can be controlled with a pair of scrollbars.
✓ JScrollPane(int vsbPolicy, int hsbPolicy) Creates an
empty (no viewport view) JScrollPane with specified
scrollbar policies.
11) Password Field : The password field is used to accept
the password for an application during the execution of a
program. It is created through JPasswordField component.
The password field is similar to textfield but the text
displayed in a password field is in the form of an echo
character (echochar). The default character is *. It means
whatever characters the user enters in this field during the
execution of the program, an echo character (usually *) will
be displayed for the same. Password field is used for the
security purpose. It does not show the character that user
types.
JPasswordField provides the following constructors:
✓ JPasswordField() Constructs a new JPasswordField,
with a default document, null starting text string, and
0 column width.
✓ JPasswordField (Document doc, String text, int
columns) Constructs a new JPasswordField that uses
the given text storage model and the given number of
columns.
✓ JPasswordField (int columns) constructs a new empty
JPasswordField with the specified number of columns.
✓ JPasswordField (String text) Constructs a new
JPasswordFieldinitialized with the specified text.
✓ JPasswordField (String text, int columns) Constructs a
new JPasswordField initialized with the specified text
and columns.
Properties :
a. Background This control is used to set the background colour for the
password field.
b. Font This control sets the font for the text ofa password field.
c. Foreground This control is used to set the colour of the text to be
displayed on password field.
d. Text This control is used to set the text for a password field.
e. echocharThis property is used to set an echo character, i.e., the character
to be displayed in the password field.
Methods:
i. voidsetEchoChar(char) This method is used to set an echo character
for the password field i.e., the character to be displayed in the
password field, when the user press any key on the keyboard.
ii. chargetEchoChar() This method returns the echo character of the
password field.
iii. char[] getPassword() This method returns the text displayed in the
password field.
iv. voidselectAll() This method selects all characters of the text field.
12) Combo Box: A Combo Box, which lets the user
choose one of several choices, can have two very different
forms. The default form is the uneditablecombobox, which
features a button and a drop-down list of values. The second
form, called the editable combobox, features a textfield with
a small button abutting it. The user can type a value in the
textfield or click the button to display a drop-down list.
Here‘s what the two forms of comboboxes look like in the
Java look and feel. Combo boxes require little screen space,
and their editable (textfield) form is useful for letting the
user quickly choose a value without limiting the user to the
displayed values. A ComboBox is created through
JComboBox component.
JComboBox provides the following
constructors:
✓ JComboBox() Creates a JComboBox with a
default data model.
✓ JComboBox (ComboBoxModel<E>aModel
)Creates a JComboBox that takes its items from
an existing ComboBoxsModel.
✓ JComboBox (E [ items) Creates a JComboBox
that contains the elements in the specified array.
✓ JComboBox(Vector<E>items) Creates
aJComboBox that contains the elements in the
specified vector.
Properties:
a. Background: It is used to set the background colour of the combo box.
b. ButtonGroup:Used to set a group of buttons in which the current control
belongs.
c. Editable: It is used to edit the contents of the textfield of the combobox.
If it is set to true, then the text given in the combobox can be edited by
the user at runtime.
d. Enabled: It is used to set the combobox as activated or deactivated on
runtime.
e. Font: Used to sent a font style for the text to be displayed.
f. Foreground: Used to set the foreground colour of the text to be
displayed.
g. Model: This property is used to specify the data model of the combobox.
h. Selectedlndex:This property is used to get or set the index specifying the
currently selected item.
i. Selectedltem:This property is used to get or set currently selected item in
the combobox.
j. Text :This property is used to specify the text to be displayed on the
textfield of the combobox.
Methods:
i. Object getSelectedltem() Returns the currently selected list object (or
item) from the data model.
ii. int getSelectedlndex() Returns an integer specifying the currently
selected list item, where 0 specifies the first item in the list, or —1 if no
item is selected or if the currently selected item is not in the list.
iii. voidsetModel (ComboBoxModel) Sets the data model that the
JComboBox uses to obtain the list of items.

13) List : A List displays a list of objects and allows the


user to select one or more items. A List is created through
JListcomponent. Lists can have many items, so they are
often put in scroll panes. In addition to JList, JComboBox
swing components also present multiple selected items to the
user. But the basic difference between list and combobox is
that list allows you to select more than one item at a time,
whereas combobox allows you to select only one item at a
time.
JList provides the following constructors:
✓ JList() Constructs a JList with an empty model.
✓ JList (ListModeldataModel) Constructs a JList that
displays the elements in the specified, non-null model.
✓ JList (Object[] listData) Constructs a JList that
displays the elements in the specified array.
✓ JList (Vector listData) Constructs a JList that displays
the elements in the specified Vector.
Properties :
a. Background: This property is used to specify the background colour of
the list.
b. ButtonGroup:This property is used to set a group of button in which the
current control belongs.
c. Model: This control is used to set an associated object that stores the data
displayed in the list.
d. Selectedlndex:This control is used to select an item initially. By default it
is set to —1 i.e., no item is selected.
e. Editable :This property can be set true or false. If it is set true, then the
test given in the list can be edited by the user at run time.
f. Enabled: Sets true or false at run time diaplay. If it is true then it does not
function at run time.
g. Font: It is used to set the font style and size of the component.
h. Foreground: It is used to set the foreground or displayed text colour of
the component.
i. Text: This control is used to set the text for a list.
j. Selectedltem:This control returns the selected items from the list.
Methods:
i. Object getSelectedvalue() This method returns the selected cell index,
when only one item is selected from the list. When multiple items are
selected, it will return the first selected value. If no items is selected, then
it will return null.
ii. ObjectgetSelectedvalues() This method returns all selected values in the
form of an array from the list, in increasing order based on their indices in
the list. When no option is selected, it will return an empty array.
DEVELOPING GENERAL APPLICATION:
Creating a new Project:
To create a new application project called “JavaApplication1”:
i. Choose File Æ New Project. Alternately, click the New Project
icon in the toolbar.
ii. From the Categories pane select Java and in the Projects pane,
choose Java Application. Æ Click Next.
iii. Enter a name (in this case JavaApplication1) in the Project Name
field and specify the project location by clicking on the Browse
button. By default the project is saved in the NetBeans Projects
folder in My Documents and so this is the default Project location
displayed in this field.
iv. Ensure that the Set as Main Project checkbox is selected and clear
the Create Main Class field.
v. Click Finish.
• NetBeans creates the JavaApplication1 folder on your system in the
designated location.
• This folder will contain all of the associated files of the project. The next
step is to create a form.
• To proceed with building our form, we need to create a container within
which we will place the other required components of the form like a
button.
• For all our applications we will choose the JFrame Form as the container
to place other components.
Creating a new form:
To create a JFrame Form container:
i. In the Projects window, right-click the Book node and choose New Æ
JFrame Form as shown in Figure .
ii. Enter Form Example 1 as the Class Name. This will be the name of your
form.
iii. Enter Book as the package. This should be the name given while creating
the Project.
iv. Click Finish.
• NetBeans creates the Form Example1 form within the application and
opens the form in the Builder. Now we are ready to add components to
our form.
Adding a Button Component to a Form:
We want to add a button so follow the given steps to add a JButton to the
form:
i. In the Palette window, select the JButton component from the Swing
Controls category (displayed in Figure ).
ii. Move the cursor over the Form. When the guidelines appear (as
displayed in Figure ) indicating that the JButton is positioned in the
desired location, click to place the button.
Attaching Code to a Form Component:
• After placing the button, the next step is to write a code to exit from the
application on the click of this button.
• To do the same, double click on the button to attach a code with the event
i.e. click of the button.
• Double clicking on the component opens up the source window and
places the cursor on the point where code is to be added. Note that certain
code is pre generated and cannot be changed.
• In the Source window add the single code line[ System.exit(0)] as shown
in Figure.
• When we click the Source button, the application‘s Java source code
in the Editor is displayed with sections of code that are automatically
generated by the NetBeans Builder indicated by gray/blue areas, called
Guarded Blocks.
• Guarded blocks are protected areas that are not editable in Source
view. Note that we can only edit code appearing in the white areas of
the Editor when in Source view.
Executing a File:
• Now that the code for the first application is ready let us test our
first application.
• To execute the application simply select Run Æ Run File or press
Shift+F6 On executing the first example, the window shown in
Figure will appear.
• Click on the button and observe the result.

• As soon as we click on the button, the application ends and we


return back to the Netbeans design window. So we learnt that the
one line of code system.exit(0) causes the application to terminate
successfully.

BASIC COMPONENT HANDLING METHODS:


• Any program that uses GUI (Graphical User Interface) such as
Java application written for windows, is event driven.
• Event describes the change of state of any object.For example,
pressing a button, entering a character in textbox.
Components of Event Handling :
Event handling has three main components
1. Events : An event is a change of state of an object.
2. Events Source : It is an object that generates an event
3. Listener :A listener is an object that listens to the event. A
listener gets notified when an event occurs.
Handling of Events:
A source generates an event and sends it to one or more listeners
registered with the source. Once event is received by the listener,
they process event and return. Events are supported by a number of
Java packages like java.util, java.awt and java.awt.event.
Basic Component Handling Methods :
To handle different swing components, there are several methods by
which the various properties of components can be handled and modified.
Some of the methods are as follows:
i. setText( ) This method is used to set the text of a component
(button, label, textfield, textarea, checkbox etc) at run time.
Syntax : Component_name.setText(“text”); Here, “text” is the
display text to be shown on a particular component.
For example, jButton1.setText (“Enter”);
In the above example, jButtonl is the component_name, “Enter” is
the text displayed on the button and setText is the method name.
ii. getText( ) This method is used to fetch out or retrive the text
contained by the specified component (button, label, textfield,
textarea, checkbox etc.,) at run time.
Syntax : Component_name.getText();
For example, String str = jTextFieldl.getText();
In the above statement ‘str’ is a string type variable which holds
the value of the text field named asjTextfieldlusinggetText()
method. By default this method returns a string value.
iii. isSelected( ) This method is used to get the current state of the
component. It returns the value of the state in the form of true or
false.
Syntax: Component_name.isSelected( );
For example, Boolean b = jCheckBoxl. isSelected( );
In the above statement ‘b’ is a Boolean type variable which
holds the current state of the component named as jCheckBoxl
using isSelected( ) method.
iv. setSelected( ) This method is used to set the current state of the
component as selected or unselected.
Syntax :Component_name.setSelected();
For example, :jCheckBoxl.setSelected (true);
In the above statement, the checkbox name as jCheckBoxl is
set to checked.
The following table summarizes the data members (properties) and methods of
all classes learnt during the course till now.

You might also like