You are on page 1of 15

Chapter 3: JAVA GUI Prog.

-Review (XII-IP)

What is JAVA?
Chapter 3:
 JAVA is an Object Oriented programming
GUI Programming- A Review language as well a platform.
 By using JAVA, we can write Platform
independent application programs, which can run
Informatics Practices Revised as per on any type of OS and Hardware.
CBSE
Class XII (CBSE Board) Curriculum  JAVA is designed to build Interactive, Dynamic
2015
and Secure applications on network computer
system.
 Java facilitates development of Multilingual
Visit www.ip4you.blogspot.com for more…. applications because JAVA uses 2-Byte UNICODE
character set, which supports almost all
Authored By:- Rajesh Kumar Mishra, PGT (Comp.Sc.) characters in almost all languages like English,
Kendriya Vidyalaya Upper Camp, Dehradun (Uttarakhand)
e-mail : rkmalld@gmail.com
Chinese, Arbic etc.

History of JAVA Characteristics of JAVA


JAVA was developed by James Gosling at Sun  Object Oriented Language
Microsystems under the Green project to write Java is Object Oriented Language (a real-world programming style)
applications for electronic devices like TV-Set Top  Open Source Product
Box etc. The language was initially called Oak and It is Open Source i.e. freely available to all with no cost.
later renamed with Java.  Write Once Run Anywhere (WORA)
James Gosling
JAVA Program can be run on any type of H/W and OS platforms i.e.
1991 James Gosling developed Oak to program consumer electronic Java programs are platform independent.
devices
 Light Weight Code
1995 Java Development Kit (JDK) 1.0 was released by the Sun Big applications can be developed with small code.
Microsystems and JAVA used as a part of Netscape web browser to
facilitate Internet Applications.  Security
1998 Sun introduced “Open” source community and produces JDK 1.2 JAVA Programs are safe and secure on Network.
(Java 2) which was released as J2EE, J2SE,J2ME version.  Interpreter & Compiler based Language
2006 Sun declared Java as Free & Open Source Software (FOSS) under JAVA uses both Compiler and Interpreter (JVM) to produce portable
GNU-GPL and NetBeans IDE was released. and platform-independent object code.
 Built-in Graphics & Supports Multimedia
2010 Sun Microsystems was owned by Oracle Corporation and now Java
Project is being governed by the Oracle. JAVA is equipped with Graphics feature. It is best for integration of
Audio, Video and graphics & animation.

Why JAVA is Platform Independent? Basics of GUI Applications


A program written in HLL must be converted into its equivalent Machine  How GUI application works ?
code, so that computer can understand and execute. This conversion is
known as Compilation. Generally, the converted machine code depends Graphical User Interface (GUI) based application
on the structure of H/w and OS platform. So that a Windows program contains Windows, Buttons, Text boxes, Dialogue
will not work on UNIX, or LINUX or Mac platform etc. Since they are
Platform dependent. boxes and Menus etc. known as GUI components.
A program written in JAVA is platform-independent i.e. they are not
While using a GUI application, when user performs
affected with changing of OS. This magic is done by using Byte code. an action, an Event is generated which causes a
Byte code is independent of the computer system it has to run upon. Message sent to application to take action.
Java compiler produces Byte code instead of native executable code  What is Event ?
which is interpreted by Java Virtual Machine (JVM) at the time of
execution. An Events refers to the occurrence of an activity by
Java Interpreter (JVM)
Java uses both compiler and interpreter. for Macintosh user like click, double click etc.
Java Java Java Byte Java Interpreter (JVM) for
Windows
 What is Message ?
Program Compiler Code
Program
Java Interpreter (JVM) for
A Message is the information/request sent to the
Unix application when event occurs.

Visit "http://ip4you.blogspot.in" for more... 1


Chapter 3: JAVA GUI Prog.-Review (XII-IP)

GUI in JAVA Basic Graphical Controls of JAVA(Swing controls)


 In JAVA, the GUI programming is done through Swing API The Java offers various Swing controls to facilitate development
(Application Programming Interface) which enables look-and feel (L&F) of GUI applications. Most commonly used controls are-
environment.  jFrame: Used as a Basic Window or form.
 Swing Controls are available with JAVA-SE as a part of Java  jLabel: Allows Non-editable text or icon to be displayed.
Foundation Classes (JFC).  jTextField: Allows user input. It is editable through text box.
 A GUI application in JAVA contains three basic elements.-  jButton: An action is generated when pushed.
1. Graphical Component (Event Source):
 jCheckBox: Allow user to select multiple choices.
It is an object that defines a screen element such as Button, Text field,
Menus etc. They are source of the Events. In GUI terminology, they  jRadioButton: They are option button which can be turned on
are also known as Widget (Window Gadget). It can be container or off. These are suitable for single selection.
control or child control.  jList: Gives a list of items from which user can select one or
2. Event: more items.
An Event (occurrence of an activity) is generated when user does  jComboBox: It gives dropdown list of items with facility to add
something like mouse click, dragging, pressing a key on the keyboard new items. It is combination of jList and jTextField.
etc.  jPanel: It is container controls which contains other controls
3. Event Handler Method: using a frame.
It contains method/functions which is attached to a component and
executed in response to an event. In Java, Listener Interface stores all A control which holds other component (child) controls, is
Event-response-methods or Event-Handler methods. called Container Control e.g. JFrame, jPanel, jDialog etc.

Using Swing Controls Events Handling in JAVA GUI Application


An event is occurrence of some activities either initiated by user or by
the system. In order to react, you need to implement some Event
jTextField jLabel
handling system in your Application. Three things are important in
Even Handling-
jRadioButton  Event Source:
It is the GUI component that generates the event, e.g. Button.
jPanel  Event Object or Message:
It is created when event occurs. It contains all the information
jCheckBox jList about the event which includes Source of event and type of event
etc.
jComboBox  Event Handler (Event Listener) Method:
It is implemented as in the form of code. It receives Event
jButton
Message and handles events through Listener Interface.
jTextArea
Event Event
Source Handler Reaction
Event Event object / Method of Event
occurrence Message (Listener)

How to use Event Handlers in NetBeans Working with Container Control- jFrame

 Right Click on desired control of the Form in Design view.  Every Swing Application must have at least one Top Level container
 Choose desired Event from the Context Menu and its Sub (jFrame, jApplet, jDialog). A Top Level Container may have Mid-Level
Menu. Container like Content Pane (jPanel, jMenuBar, jScrollBar etc.) or
Components (jButton, jTextField etc.)
 When you click on desired Event, it opens source Code editor
 A Frame (jFrame) is a Top Level (Desktop) container control having
with default Handler Name, where you can type TO DO code Title Border and other Properties.
for the Handler. ActionPerformed is commonly used Listener.
Properties Value Description
 you will found a code window along with prototyped method
to perform actions defined by you. You may write commands title Text Sets the title (appears on the
top) of the frame
to be executed in //TODO section.
Control Listener Event
cursor Crosshair, East Resize, Specifies the type of mouse
Name Name Name West Resize, Northwest cursor when mouse moves on
Resize, Move, Hand, the frame.
Wait, Default cursor
Resizable True /false If checked, allows resizing of
the frame

Commands to defaultCloseOperation DO_NOTHING, HIDE, Defines the action when close


be executed DISPOSE, button is pressed.
EXIT_ON_CLOSE

Visit "http://ip4you.blogspot.in" for more... 2


Chapter 3: JAVA GUI Prog.-Review (XII-IP)

Working with Panel- jPanel Working with Push Buttons- jButton


 A Panel is container that holds other components displayed on the
frame.  A button belongs to JButton class of Swing control API.
 To add Panel, just drag JPanel component on the frame and resize it.  It is mostly used action component, and can be used to trigger
 Drag other components (jButton, jTextFields etc.) from the Swing the associated events/methods in the application, when user
Control Box and drop it onto panel.
clicks.
Properties Value Description
Properties Value Description
Background Color Sets the background color.
background Color Sets the background color. It works
Border No Border, Bevel Border, Specifies the type of Border applies only when contentAreaFilled is set
Compound Border, Empty on the boundary of the panel. to True.
order, Etched Border, Line
Border, Titled Border etc. foreground Color Sets the foreground color.

Foreground Color Sets the foreground color. toolTipText Text Sets the text for tool tip.

ToolTipText Text Sets the text for tooltip. Text Text Caption of button.

MinimumSize X, Y values Defines the minimum width and mnemonic Shortcut or Access key Assign Shortcut key (Alt +key).
height (x,y) in Twips( 1/1440 inch) enabled True/False Determines whether Active or not.
MaximumSize X, Y values Defines the maximum(x,y) size. font Font name Sets the font for the text of button.
PreferredSize X, Y values Defines the preferred (x,y) size.

Working with jButtons.. Working with jLabel control


 Commonly used methods of JButton.
A Label control belongs to JLabel class and
Method Description used to display non-editable text. The
setText( ) Sets the text displayed on the button.
Ex. jButton1.setText(“You Clicked Me”);
text to be displayed is controlled by text
getText( ) Returns the text displayed on the button.
property (design time) and setText()
Ex. String result=jButton1.getText(); method at run time. jLabel offers the
jLabel1.setText(result);
setIcon( ) Sets the icon file to be displayed.
following features-
Ex. jButton1.setIcon( new ImageIcon
(“c:\\abc.png”));
It can display Text or Image or both.
setEnabled( boolean) Enables or disables the button. It may have bordered appearance.
Ex. jButton1.setEnabled(false);
Supports HTML for formatted text.
setVisible(boolean) Makes the button visible or invisible.
Ex. jButton1.isVisible(false)

Commonly used Properties & Methods of jLabel Displaying Image with jLabel
Properties Value Description  Setting up Image at Design Time :-
background Color Sets the background color. It works only  Add jLabel control and click on ellipse (…) of Icon
when opaque is set to True.
property in property window.
foreground Color Sets the foreground color.
 In the dialogue box, select Image chooser option.
Text Text Sets the text to be displayed.
 Specify the path and file name in External Image option.
Font Font name and size Defines the font and size of text.
 Open source editor and go to top of the code and write-
enabled True/False Determines whether Active or not
import javax.swing.ImageIcon;
Icon Image file to be displayed Specifies the image file to be displayed.
 Setting up Image at Run time:-
Methods Description  Import the javax library by placing following command at
setText(String) Sets the string of text to be displayed. top of the code.
Ex. jLabel1.setText(“I am OK”); import.javax.swing.ImageIcon;
getText() Returns the text displayed by the label.  Use the following command in a Event method where
Ex. String st=jLabel1.getText(); image to be displayed or changed.
setVisible(boolean) Makes the Label visible or invisible. jLabel.setIcon(new ImageIcom(“c:\\abc.png”))
Ex. jLabel1.setVisible(false);

Visit "http://ip4you.blogspot.in" for more... 3


Chapter 3: JAVA GUI Prog.-Review (XII-IP)

Working with jTextField control Commonly used Properties of jTextField


Properties Value Description
A jTextField is a versatile control, used to get background Color Sets the background color.
input from user or to display text. It is an foreground Color Sets the foreground color.
object of jTextField class and allow the user to Text Text Sets the text to be displayed.
enter a single line of text. Font Font name and size Defines the font and size of text.
enabled True/False Determines whether Active or not
jTextField offers the following features-
editable True/False Allow user to edit text, if set to true.
 You can insert and select text.
Methods Description
 You can scroll the text, if not fit in visible area. setText(String) Sets the string of text to be displayed.
Ex. jTextField1.setText(“I am OK”);
 You can use selected text in other application
getText() Returns the text displayed by the label.
using clipboard. Ex. String st=jTextField1.getText();
isEditable( ) Returns the setting whether it is editable or not.
Ex. Boolean b=jTextField1.isEditable( );
isEnabled( ) Returns the setting whether it is enabled or not.
Ex. Boolean b=jTextField1.isEnabled( );

Text interaction using jTextFields Working with jCheckBox control


In GUI application often we require to store the values of text fields to variable or
vice-versa. Java offers three method for this purpose- A jCheckBox control belongs to JCheckBox class of
 getText(): Swing controls. It indicates whether a particular
It returns the text stored in the text based GUI components like Text Field, condition is on or off. You can use Check boxes to
Text Area, Button, Label, Check Box and Radio Button etc. in string type.
e.g. String str1=jTextField1.getText(); accept user’s choice in terms of true/false or yes/no
 parse…….() options.
This method convert textual data from GUI component in to numeric type.
Byte.parseByte(String s) – string into byte.
Check Boxes may works independently to each other,
Short.parseShort(String s) – string into short. so that any number of check boxes can be selected
Integer.parseInt(string s) – string into integer. at the same time.
Long.parseLong(string s) – string into long.
Float.parseFloat(string s) – string into float. Some features of jCheckBox control’s are-
Double.parseDouble(string s) – string into double.  It can be used to input True/False or Yes/No typed
e.g. int age=Integer.parseInt(jTextField1.getText());
 setText() input to the application.
This method stores string into GUI component.  Multiple check boxes can be selected at the same
e.g. jTextField1.setText(“Amitabh”); Alternatively it can written as-
jLabel1.setText(“”+payment); jLabel1.setText(Integer.toString time.
(payment));

Commonly used Properties of jCheckBox Commonly used Methods of jCheckBox


Properties Value Description Methods Description

background Color Sets the background color. setText(String) Sets the string of text to be displayed.
foreground Color Sets the foreground color. Ex. jCheckBox1.setText(“Computer”);
Text Text Sets the text to be displayed. getText() Returns the text displayed by on the check box.
Label Text/Picture Sets the text/Picture to be Ex. String st=jCheckBox1.getText();
displayed.
setEnabled() Sets the check box enables, if true is given.
Font Font name and Defines the font and size of text. Ex. jCheckBox1.setEnabled(true);
size
isEnabled( ) Returns the state whether check box is enabled.
enabled True/False Determines whether Active or not
Ex. Boolean st=jCheckBox1.isEnabled();
mnemonic Character Specifies the shortcut (access) key
setSelected() Sets the check box selected, if true is given.
selected True/false Check box will be selected, if set to Ex. jCheckBox1.setSelected(true);
true. (default is false)
isSelected( ) Returns the state whether check box is selected or not.
Button Group Button Group Adds Check Boxes in a Group
Ex. If(jCheckBox1.isSelected())
name
{ …… }

Visit "http://ip4you.blogspot.in" for more... 4


Chapter 3: JAVA GUI Prog.-Review (XII-IP)

Working with jRadioButton control Commonly used Properties of jRadioButton

A jRadioButton control belongs to JRadioButton class of Properties Value Description


Swing controls. It is used to get choices from the Background Color Sets the background color.
user. Generally, It is used as a grouped control, so Foreground Color Sets the foreground color.
that only one can be selected at a time. ButtonGroup Name of control Specifies the name of group to which
By default, jButtons are independent control. To make Radio Button belongs.

tem dependent, Radio Buttons should be kept in a Text Text Sets the text to be displayed.

ButtonGroup container control, so that only one Label Text/Picture Sets the text/Picture to be displayed.

button can be selected at a time in a group. Font Font name and size Defines the font and size of text.
Enabled True/False Determines whether Active or not
Some features of jRadioButton control’s are-
Mnemonic Character Specifies the shortcut (access) key
 It can be used to get true/false or yes/no choice-
Selected True/false Button will be selected, if set to true.
typed input for the application. (default is false)
 They must be kept in a Button Group container
You must add a ButtonGroup control to the frame to group the Radio
control to form a group. Buttons by using ButtonGroup property to facilitate only-one selection.

Commonly used Methods of jRadioButton Working with jList control


Methods Description A List (or List box) is box shaped control containing list
setText(String) Sets the string of text to be displayed. of objects, from which single or multiple selection
Ex. jRadioButton1.setText(“Science”); can be made. jList control offers the following
getText() Returns the text displayed on the Button. features-
Ex. String st=jRadioButton1.getText();  A box shaped control capable to displaying a list of
setEnabled() Sets the Radio Button enables, if true is given. choices (Text or graphics/images)
Ex. jRadioButton1.setEnabled(true);  It allows single or multiple selection of items using
isEnabled( ) Returns the state whether radio button is enabled. mouse.
Ex. boolean st=jRadioButton1.isEnabled();
 Equipped with built-in scroll bar to view a large list.
setSelected() Sets the Radio Button selected, if true is given.
Ex. jRadioButton1.setSelected(true);  valueChanged() method of ListSelection Listener is
isSelected( ) Returns the state whether Radio Button is selected
used to handle the JList events
or not.  After attaching a jList control, Model property is
Ex. if(jRadioButton1.isSelected()) used to specify the list items at design time.
{……… }

Commonly used Properties of jList Commonly used Methods of jList


Properties Value Description Methods Description
Background Color Sets the background color.
clearSelection() Clears the selection in the list.
Foreground Color Sets the foreground color.
Ex. jList1.clearSelection();
model Items for Choice Specifies the items to be displayed as
a choice. getSelectedIndex() Returns the index of selected items in single
selectionMode SINGLE User may select single item. selection mode. Returns -1, if selection is not
SINGLE_INTERVAL User may select Single range of items made.
by holding SHIFT key. int x= jList1.getSlectedIndex();
MULTIPLE_INTERVAL User may select Multiple range of if (jList1.getSelectedIndex()==1) {…}
Items by holding CTRL key
getSelectedValue() Returns the value or selected items.
selectedIndex Value Specifies the index of Items to appear String st= (String) jList1.getSlectedValue();
selected.
if (jList1.getSelectedValue()==“Apple”){…}
(default is -1 since no items is
selected.) isSelectedIndex(int) Returns True if given Index is selected.
font Font name Specifies font’s name and size etc. Ex: if (jList1.isSlectedIndex(2)) {…}
enabled True/False Specifies that list will be active or not. Other methods like isEnabled(), setVisible(), setEnabled() etc. can be used with
jList control.

Visit "http://ip4you.blogspot.in" for more... 5


Chapter 3: JAVA GUI Prog.-Review (XII-IP)

How to handle Selections in the jList Working with jComboBox control


Suppose we want to display A jComboBox (TextField + List Box) is a control which offers
jList1 jTextField1
the index and value of the list of choice which can be selected through a drop-
selected items i.e. 2 and Apple down list.
2
Mango
‘Banana’ in Text Fields when By default it is an un-editable control, but we can make it
user selects an items in the Banana
Banana editable by setting ‘editable‘ property True.
list. Orange
jComboBox1ActionPerformed(..) method can be handled when
Papaya jTextField2
user selects an item from the combo.
Exit
Difference Between List & Combo Box
 In Combo Box, user can select and edit an item but in List,
Just Right Click on jList control and choose Items can be selected and can not be edited.
Events->ListSelection->ValueChanged  List does not offers Text Field where as Combo Box offers Text
Write the following code in //TO DO Section…………. Field.
int x = jList1.getSelectedIndex();
String st = (String ) jList1.getSelectedValue();  Combo Box offers a Drop-down list, so that it takes less space
jTextField1.setText(“”+x); in the frame, but List this feature is not available.
jTextField2.setText(st);  List allows more than one items to be selected, but in Combo
Box, only one item can be selected.

Commonly used Properties of jComboBox Commonly used Methods of jComboBox


Methods Description
Properties Value Description
getSelectedIndex() Returns the index of selected items.
Background Color Sets the background color.
if (jComboBox1.getSlectedItem()==1) {…};
Foreground Color Sets the foreground color. getSelectedItem() Returns the selected items.
model Items for Specifies the items to be displayed as a if (jComboBox1.getSlectedItem()==“Mango”)
Choice choice. {…… …};
selectedIndex Value Specifies the index of Items to appear isEditable() Returns True, if Combo box is editable.
selected (default is -1 since no items is
addItem(string) Adds an item to the choice list at the end.
selected.)
selectedItem String/values Specifies the indices of selected items. Ex. jComboBox1.addItem(“Banana”);
getItemCount() Returns the number of items in the combo Box.
font Font name Specifies font’s name and size etc.
int x = jComboBox1.getItemCount();
editable True/False If True, you can edit/type new value or getItemAt(int) Returns the items at specified index.
choice in the Combo Box. String st=jComboBox1.getItemAt(2);
enabled True/False Specifies that list will be active or not. removeAllItems() Removes all the items from combo.
removeItemAt(index) Removes items for given index from the combo.
Ex. jComboBox1.removeItemAt(2);

Working with jTextArea control Commonly used Properties of jTextArea


A jTextArea control is a multi-line text component, Properties Value Description
used to get input from user or to display text. It Background Color Sets the background color.
is an object of JTextArea class. Foreground Color Sets the foreground color.
By default, it does not wrap (move next line) lines LineWrap True/ false Defines Wrapping feature
enable/disable
of text like word processor, if line goes beyond
Rows number Set the number of rows of in text
the boundary. Some features are- area
 You can insert and select multiple line of text. Columns number Sets the number of columns
Text Text Sets the text to be displayed.
 You can wrap text, if not fit in visible area.
Font Font name and Defines the font and size of text.
 You can use selected text in other application size
using clipboard. Enabled True/False Determines whether Active or not
Editable True/False Allow user to edit text, if set to
true.

Visit "http://ip4you.blogspot.in" for more... 6


Chapter 3: JAVA GUI Prog.-Review (XII-IP)

Commonly used Methods of jTextArea Working with jPasswordField Control


Methods Description  A jPasswordField is a type of Text field that shows Encrypted
setText() Sets the string of text to be displayed.
text (actual text is not shown for security purpose) like ‘*’ or
Ex. jTextArea1.setText(“I am OK”); any other specified character as you type.
getText() Returns the text displayed by the label.  The character displayed in place of typed character is called
echo Character, which is controlled by echoChar property.
setEditable() Sets the TextArea editable.
isEditable( ) Returns the setting whether it is editable or not. Properties Value Description
Ex. boolean b=jTextArea.isEditable( ); Background Color Sets the background color.
append() Adds specified text in the text area.
Ex: jTaxtArea1.append(“How are you”);
Foreground Color Sets the foreground color.

Insert(string, int) Inserts specified text at given position. Use 0 to insert at Text Text Sets the text to be displayed.
top. Font Font and size Defines the font and size of text.
Ex. jTextArea1.insert(“Amit”,1);
enabled True/False Determines whether Active or not
setLineWrap() Enables or disables line wrap feature. editable True/False Allow user to edit text, if set to true.
Ex. jTextArea1.setLineWrap(true);
echoChar Character Specifies the character to be displayed
isEnabled( ) Returns the status whether it is enabled or not. in place of typed character.
Ex. boolean b=jTextArea.isEnabled( );

Commonly used Methods of jPasswordField JOptionPane : Built-In Dialog of JAVA

Methods Description
JOptionPane allows to create pop-up window or dialog with
predefined style.
setEchoChar(char) Sets the echo character.
Ex. jPasswordField1.setEchoChar( ‘#’ ); Java provides following types of Dialogs which can be used as
per requirement.
getPassword( )* Returns the text displayed by the password field.
String pwd= new String (jPasswordField1.getPassword());
Dialog Method Description
Types
* getPassword() method returns a character array, not a string. To store
Message showMessageDialog() Used to inform user by
it in a string variable you need to use constructor of string.
Dialog displaying a message. It
Comparing Strings in JAVA includes OK button only.
In Java two strings can not be compared directly, by using == operator. Input Dialog showInputDialog() Used to get user input using
Text Field.
Two methods equals( ) and compareTo( ) are used for this purpose.
Confirm Dialog showConfirmDialog() Used to ask a user to confirm
equals() returns TRUE/FALSE but compareTo() returns 0 if both are some information with Yes/No
equal otherwise non-zero value is returned. or OK/Cancel buttons.
Ex. if (pwd.equals(“abc”)) {……} else {…..}

JOptionPane Dialog Types: Working with JOptionPane

To use the JoptionPane dialog control in the application, you must


import the following class(s).
import.javax.swing.JOptionPane;
In general, the following syntax of methods along with optional
parameters can be used-
JoptionPane.show……([frame name],<“Message”> [,<“Title”>] );
Message Dialog Confirm Dialog
 Frame Name: Generally null is used to indicate current frame.
 Message: User given string to covey the message.
Title  Title: Text to be displayed as Title on the Title bar.
Message to
be displayed Example(s):
Icon JOptinPane.showMessageDialog(null,”JAVA Welcomes You”);
Text JOptinPane.showMessageDialog (null,”My Name is “+name);
Buttons
Field String n= JOptinPane.showInputDialog (null,”Enter your Name ?”);
String n= JOptinPane.showInputDialog (null,”Enter your Name ?”, “Input Name”);
Input Dialog int ch=JOptinPane.showConfirmDialog(null,”Want to exit ?”);
int ch=JOptinPane.showConfirmDialog(null,”Want to exit ?”,”Confirm ?”);

Visit "http://ip4you.blogspot.in" for more... 7


Chapter 3: JAVA GUI Prog.-Review (XII-IP)

Return Value of JOptionPane dialog Return Value of JOptionPane dialog


Value returned by Input Dialog:  Value returned by Confirm Dialog:
ShowInputDialog() returns a string value which can be Sometimes it is required to check the response of user i.e. which
directly assigned on a string type variable. You may use button is pressed, so that application can respond accordingly.
parse…() method to convert it into other data types like int .showConfirmDialog() returns int type value which can be compared
or float etc. for further use in the application. with the following constants to determine the status of button
pressed by the user.
String n=JOptionPane.showInputDialog(null, ”Enter Name? ”); Returned Value Indication
JOptionPane.YES_OPTION YES button is pressed
private void jButton1ActionPerformed(…) { JOptionPane.OK_OPTION OK button is pressed
// Program to calculate area of circle using Input dialog JOptionPane.NO_OPTION NO button is pressed
String str=JOptionPane.showInputDialog(null, ”Enter radius JOptionPane.CANCEL_OPTION CANCEL button is pressed
of circle ?”);
JOptionPane.CLOSE_OPTION User closed the dialog using X button
int radius=Integer.parseInt(str);
float area=(22/7)*(radius*radius); int ans=JOptionPane.showConfirmDialog(null, ”Want to exit ?”);
JOptionPane.showMessageDialog(null, “Area of circle=“+area); If (ans==JOptionPane.YES_OPTION)
} System.exit(0);

JDialog – A Simple General purpose dialog Displaying Text/Values in JAVA GUIs


 The JDialog is a swing window dialog equipped with Minimise, Maximise In GUI application often we require to display an information
and Close functionality. as a message or value stored in a variable. The following
 JDialog creates a standard pop-up window for displaying desired three ways are used –
information related to your application.
 Using jTextFields or jLabel Controls-
 Steps to Attach a JDialog Control-
1. Design an application as required and drag Dialog control from swing
jTextField1.setText(“Area =”+a);
palette and drop it into the application. jLabel1.setText(“Hello Java”);
2. To open Dialog frame, double click on jDialog node under other
 Using Dialog Box-
component in Inspector window.
3. Attach message button and title in Dialog control as per requirement. JOptionPane.showMessageDialog(null, “Hello.. “);
4. Attach the following ActionPerformed event handler of attached JOptionPane.showMessageDialog(null, “Area=“+a);
button.  Displaying result at output window using System.out.print()
jDialog1.dispose(); method-
5. Now switch to Frame by double clicking on JFrame node in Inspector
window.
e.g. System.out.print(“Hello…”);
6. Attach the following code on button from where you want to run the System.out.println(“Area=”+a);
dialog.
jDialog.setVisible(true);

JAVA Tokens Keywords in Java

The smallest individual unit in a program Keywords are the reserve words that
is known as Token. It may any word, have a special meaning to the compiler.
symbols or punctuation mark etc.
Key words can’t be used as identifiers or
Following types of tokens used in Java- variable name etc.
Keywords
Commonly used key words are-
Identifiers
char, long, for, case, if, double, int,
Literals
short, void, main, while , new etc.
Punctuators (; [] etc)
Operators (+,-,/,*, =, == etc.)

Visit "http://ip4you.blogspot.in" for more... 8


Chapter 3: JAVA GUI Prog.-Review (XII-IP)

Identifiers in Java Literals in Java


 Identifiers are fundamental building block of program and
used as names given to variables, objects, classes and
functions etc. Literals or constants are data items that
 The following rules must be followed while using have fixed data value.
identifiers.
 Identifiers may have alphabets, digits and dollar ($),
Java allows several types of literals like-
underscore (_) sign. Integer Literals
 They must not be Java keywords. Floating Literals
 They must not begin with digit.
 They can be of any length.
Boolean Literals
 They are Case Sensitive ie. Age is different from age. Character Literals
 Example of Valid identifiers- String Literals
MyFile, Date9_7_7, z2t09, A_2_Z, $1_to_100, _chk etc.
The null literals
 Example of Invalid identifiers-
Date-RAC, 29abc, My.File, break, for

Integer Literals Floating / Real Literals

 An integer constant or literals must have at  A real literals are fractional numbers having at least one
digit before and after decimal point with + or – sign.
least one +/- digit without decimal point. The following are valid real numbers-
 Java allows three types of integer literals - 2.0, 17.5, -13.0. -0.00626
 Decimal Integer Literals (Base 10) The following are invalid real numbers-
e.g. 1234, 41, +97, -17 etc. 7, 7. , +17/2 and 17,250.26 etc.
 Octal Integer Literals (Base 8)
 A real literals may be represented in Exponent form having
e.g.010, 014 (Octal must start with 0) Matissa and exponent with base 10 (E). Mantissa may be a
 Hexadecimal Integer Literals (Base 16) proper real numbers while exponent must be integer.
e.g. 0xC, 0xab (Hex numbers must starts with 0x) The following are valid real in exponent form-
 L or U suffix can used to represent long and 152E05, 1.52E07, 0.152E08, -0.12E-3, 1.5E+8
unsigned literals respectively. The following are invalid real exponent numbers-
172.E5, 1.7E, 0.17E2.3, 17,22E05, .25E-7

Other Literals Data types in JAVA


 The Boolean Literals represents either TRUE or FALSE. It always
Data types are means to identify the type of data and
Boolean type.
 A null literals indicates nothing. It always null type.
associated operations of handling it.
 Character Literals must contain one character and must enclosed Java offers two types of data types.
in single quotation mark.  Primitive:
e.g. ‘a’, ‘%’ , ‘9’ , ‘\\’ etc.
Java allows some non-graphic characters (which can not be typed
These are in-built data types offered by the compiler.
directly through keyboard) by using Escape sequence (\) . Java supports 8 primitive data types e.g. byte, short,
The following Escape characters are commonly used in Java. int, long, float, double, char, boolean.
\a (alert), \b (backspace), \f (Form feed),  Reference:
\n (new line), \r (return key), \t (Horizontal tab),
These are constructed by using primitive data types,
\v (vertical tab), \\ (back slash), \’ (single quote) ,
as per user need. Reference data types store the
\” (double quote) , \? (question mark), \0 (null) etc.
memory address of an object. Class, Interface and
Array are the example of Reference Data types.
 String Literals is a sequence of zero or more characters enclosed
in double quotes. E.g. “abs”, “amit” , “1234” , “12 A” etc.

Visit "http://ip4you.blogspot.in" for more... 9


Chapter 3: JAVA GUI Prog.-Review (XII-IP)

Data Types in Java Primitive Data types


Type Size Description Range
Data Types byte 1 Byte Byte integer -128 to +127
Primitive
Reference
short 2 Byte Short integer -32768 to +32767
(intrinsic/Fundamentals)
int 4 Byte integer -231 to 231-1
Numeric Non-Numeric Classes Interface Arrays
long 8 Byte Long integer -263 to 263-1
Integral Fractional Character Boolean float 4 Byte Single precision floating -3.4x10-38 to +3.4x1038
point (up to 6 digit)
Byte float char
double 8 Byte Double precision floating -1.8x10-308 to +1.8x10308
short double (up to 15 digit)

int
char 2 Byte Single character 0 to 65536
Boolean 1 Byte Logical Boolean values True or False
long

 L suffix can used to indicate the value as long.


 By default Java assume frictional value as double, F and D suffix can be
String Data type is also used in Java as Reference data type
used with number to indicate float and double values respectively.

Working with Variables Operators in Java


 A variable is named memory location, which holds a data
value of a particular data type.  The operators are symbols or words, which
 Declaration and Initialization of variable- perform specified operation on its operands.
<data type> <variable Name>;
int age;
 Operators may Unary, Binary and Turnery as per
double amount; number of operands it requires.
double price=214.70, discount =0.12;
String name=“Amitabh”  Java offers the following types of Operators:-
long x=25L;  Arithmetic Operator
byte a=3;
float x= a+b;  Increment/Decrement Operator
 By default all Numeric variables initialized with 0, and  Relational or Comparison Operators
character and reference variable with null, boolean with false,  Logical Operators
if it is not initialized.  Assignment Operators
 The keyword final can be used with variable declaration to
 Other Operators.
indicate constant.
E.g. final double SERVICE_TAX=0.020;

1. Arithmetic Operators 2. Increment & Decrement Operator

+ Unary plus Represents positive int a=+25;  Java supports ++ and -- operator which adds
values. or subtract 1 from its operand. i.e.
- Unary minus Represents negative int a=-25; a=a+1 equivalent to ++a or a++
values. a=a-1 equivalent to --a or a--
+ Addition Adds two values int x= a+b;  ++ or -- operator may used in Pre or Post
- Subtraction Subtract second int x=a-b; form.
operands from first.
* Multiplication Multiplies two values int x= a*b;
++a or --a (increase/decrease before use)
/ Division Divides first operand int x=a/b; a++ or a– (increase/decrease after use)
by second
Ex. Find value of P? (initially n=8 and p=4)
% Modulus Finds remainder after int x= a%b;
(remainder) division.
p=p* --n;  28
+ Concatenate or Adds two strings “ab”+”cd”  ”abcd”
p=p* n--;  32
String addition “25”+”12”  ”2512” Ex. Evaluate x=++y + 2y if y=6.
“”+5  ”5” =7+14 = 21
“”+5+”xyz”  ”5xyz”

Visit "http://ip4you.blogspot.in" for more... 10


Chapter 3: JAVA GUI Prog.-Review (XII-IP)

3.Relational Operator 4.Logical Operator


 Relational operators returns true or false as per the  Logical operators returns true or false as per the condition of
relation between operands. operands. These are used to design more complex conditions.
 Java offers the following six relational operators.  Java offers the following six (5 binary and 1 unary) logical
< less than operators.
<= less than or equal to
Operator Name use Returns true if
> greater than
&& And x&&y X and y both true
>= greater than or equal to
== equal to || Or x||y Either x or y is true
!= not equal to ! Not !x X is false
Relational operators solved from left to right. & Bitwise and x&y X and y both true
Ex: 3>=3 true | Bitwise or x|y Either x or y is true
3!=3 false ^ Exclusive or x^y If x and y are different
a==b true if a and b have the same value.
Ex: 5>8 || 5<2 (false) 1==0||0>1 (false)
a<b<c => (a<b)<c true if a is smallest.
6<9 && 4>2 (true) 6==3&&4==4 (false)
!(5!=0) (false) !(5>9) (true)

5.Assignment Operator 6. Other Operators


 In Java = operator is known as Assignment operator, it  In Java some other operators are also used for various
assigns right hand value to left hand variables.
operations. Some operators are-
Ex: int x=5;
z= x+y; Operator Equivalent to
 Java offers some special shortened Assignment operators, ?: Shortcut of If condition (turnery operator)
which are used to assign values on a variable. <Condition> ? <true action>:<false action>
[] Used to declare array or access array element
Operator use Equivalent to
. Used to form qualified name (refer)
+= X+=y X=X+Y (type) Converts values as per given data type
-= X-=y X=X-Y new Creates a new object
*= X*=y X=X*Y instanceof Determines whether the object is an instance of a class.
/= x/=y X=X/Y
%= X%=y X=X%Y Ex. result = marks>=50 ? ‘P’ : ‘F’
Ex: x-=10 => x=x-10 6>4 ? 9:7 evaluates 9 because 6>4 is true.
x%=y => x=x%y

Operator’s Precedence Expression in Java


Operator’s precedence determines the order in which expressions are evaluated.
There is certain rules called Precedence for evaluating a complex expression.
 An expression is a valid combination of operators, constants
e.g. y=6+4/2 (why 8 not 5 ?) and variable and keywords i.e. combination of Java tokens.
 In java, three types of expressions are used.
Operators Remark Associativity
 Arithmetic Expression
. [] () () used to make a group, [] used for array and . L to R
Is used to access member of object
Arithmetic expression may contain one or more numeric variables,
literals and operators. Two operands or operators should not occur
++ -- ! Increment/Decrement Operator, Not Operator R to L in continuation.
Returns true or false based on operands
e.g. x+*y and q(a+b-z/4) are invalid expressions.
New, (type) New is used to create object and (type) is used R to L
to convert data into other types. Pure expression: when all operands are of same type.
* / % Multiplication, division and modulus L to R Mixed expressions: when operands are of different data types.
+ - Addition and Subtraction R to L  Logical Expression
== != Equality and not equality L to R Logical or Boolean expression may have two or more simple
& , ^, | Bitwise And, Bitwise Exclusive Or , Bitwise or L to R expressions joined with relational or logical operators.
&& Logical And L to R e.g.  x>y  (y+z)>=(x/z)  x||y && z
|| Logical or L to R  Compound Expression
?: Shortcut of IF R to L It is combination of two or more simple expressions.
=, +=, -=, *=, /=, %= Various Assignment operators R to L e.g.  (a+b)/(c+d)  (a>b)||(b<c)

Visit "http://ip4you.blogspot.in" for more... 11


Chapter 3: JAVA GUI Prog.-Review (XII-IP)

Data Type Conversion in JAVA Implicit Type Conversion

The process of converting one  It is performed by the compiler, when different data
predefined type into another is called types are intermixed in an expression. It is also
called Coercian.
type conversion.
 In Implicit conversion, all operands are promoted
In mixed expression, various types of (Coercion) up to the largest data type in the
constant and variables are converted expression.
into same type before evaluation. Ex. Consider the given expression, where f is float, d is double
Java facilitates two types of conversion. and I is integer data type.
Result= (f * d) - ( f + i) + ( f / i)
 Implicit type conversion
 Explicit type conversion double float float

double

Explicit Conversion in JAVA JAVA Statements


 An explicit conversion is user defined that forces to convert
an operand to a specific data type by (type) cast.  A statement in Java is a complete unit of execution. It
may consists of Expression, Declaration, Control flow
e.g. (float) (x/2) suppose x is integer.
statements and must be ended with semicolon (;)
The result of x/2 is converted in float otherwise it will give
 Statements forms a block enclosed within { }. Even a
integer result.
block may have no statement (empty).
 In pure expression the resultant is given as expression’s E.g. If(a>b)
data type.
{…….
e.g. 100/11 will give 9 not 9.999 (since both are integer) …….
 In mixed expression the implicit conversion is applied }
(largest type promotion)  Just Think….. Why?
e.g. int a, mb=2, k=4 then evaluate System.out.print(‘h’+’a’) will give 169
a=mb*3/4+k/4+8-mb+5/8
System.out.print(“ ”+‘h’+’a’) will give ha
=2*3/4+4/4+8–2+5/8
=6/4+1+8–2+5/8 System.out.print(“2+2=”+2+2) will give 2+2=22
=1+1+8–2+0 (6/4 will give 1 ) System.out.print(“2+2=”+(2+2)) will give 2+2=4
=8

Programming Constructs in JAVA Diagrammatic Representation


 In general a program is executed from begin to end.
Statement 1
But sometimes it required to execute the program True
Condition Statement (s)
selectively or repeatedly as per defined condition. Statement 2
False
Such constructs are called control statements.
 The programming constructs in Java, are categorized into - Statement 3 Statement (s)
 Sequence:
Statements are executed in top-down sequence.
Sequence construct Selection construct
 Selection (conditional):
Execution of statement depends on the condition,
whether it is True or False.
(Ex. if.., if…else, switch constructs) False True
Iteration Condition
 Iteration (Looping):
Construct
Statement is executed multiple times (repetition) till
the defined condition True or False. Exit from Statement (s)
loop
(Ex. for.. , while… , do..while loop constructs)

Visit "http://ip4you.blogspot.in" for more... 12


Chapter 3: JAVA GUI Prog.-Review (XII-IP)

Selection statement (if..) Selection statement (if..else..)


 The if… statement is used to test a condition. If defined  The if…else.. also tests condition. If defined condition is
condition is true the statements are executed otherwise true the statements in True block are executed otherwise
they are ignored. else block is executed.
 The condition may be simple or complex (using &&, || etc.) if (condition) if ( num>0) {
and must be enclosed in ( ). { jLable1.setText(“Number is positive”);
 Expression defined as condition must be evaluated as True statement 1 ; }
or False. …………….. else
Syntax
if ( num>0) { {
}
if (condition) jLable1.setText(“Number is positive”); jLable1.setText(“Number is zero or negative”);
else
}
{ } {
statement 2; if ( age>=18)
statement 1 ; if ( ch>=‘0’ && ch<=‘9’ ) {
……………. jLable1.setText(“Eligible to Vote”);
…………….. jLable1.setText(“It is digit”); } else
} } jLable1.setText(“Not eligible to Vote”);
In case of single statement in if… the use of {} is optional. In case of single statement {} is optional.

Nested if... If…else…If ladder


 An if… or if..else.. may have another if.. Statement in its true  When a else block contains another if.. and this nested else block
may have another if and so on. This nesting is often known as
block or in false block. It is known as Nesting of if (placing an if..else..if ladder or staircase.
if inside another if).
if (condition1) if (day==1)
if (condition1){ if ( num>0) statement 1; jLable.setText(“Sunday”);
if(condition 2) { else else
if (day==2)
{ …….. } jLable1.setText(“Number is positive”); if (condition 2)
jLable.setText(“Monday”);
else } statement 2; else
{ ……… } else else if (day==3)
if (condition 3) jLable.setText(“Tuesday”);
} { if (num<0)
else
jLable1.setText(“Number is negative”); statement 3;
else{ if(day==4)
else else jLable.setText(“Wednesday ”);
if(condition 3) else
jLable1.setText(“Number is zero”); if(condition 4)
{ …….. } statement 4;
if(day==5)
else } jLable.setText(“Thrusday”);
……… else
{ ……… } ……… if(day==6)
jLable.setText(“Friday”);
else
Nested if.. block else
} statement n; jLable.setText(“Saturday”);

Conditional operator and if.. statement The switch statement


 The ? : (conditional operator) may be used as alternative to  Multi-branching selection can be made in Java by using switch statement.
if..else.. statement in Java.  It test successively, the value of an expression (short, int, long or char
type), when match is found, the statements associated with constant is
 In contrast to if…, ?: is more concise and compact code it is executed. switch (day)
less functional than ‘if’. switch (<expression>) { case 1 : Dow=“Sunday”;
 ?: produces an expression so that a single value may be { case <const 1> : statement (s); break;
case 2 : Dow=“Monday”;
incorporated whereas if.. is more flexible, whereas you may break; break;
use multiple statements, expressions and assignments. case <const 2> : statement (s); case 3 : Dow=“Tuesday”;
 When ?: is used as nested form, it becomes more complex break; break;
case 4 : Dow=“Wednesday”;
and difficult to understand. case <const 2> : statement (s);
break;
break; case 5 : Dow=“Thursday”;
Syntax break;
if ( a>b) ……….. case 6 : Dow=“Friday”;
Expression 1 ? Expression 2: expression 3; [default : statement (s);] break;
c=a; }
case 7 : Dow=“Saturday”;
break;
else C = a>b ? a : b ; default : Dow=“Wrong Input”;
1. No two identical constant can be used. }
c=b; 2. Default.. is optional and may be anywhere jLable.setText(“Weak day”+Dow);
in switch block, if used.

Visit "http://ip4you.blogspot.in" for more... 13


Chapter 3: JAVA GUI Prog.-Review (XII-IP)

Switch and if..else statement Iteration (looping) statements


The switch and if..else both are used to make a selection construct
in Java, but there some differences.
 Iteration or looping allow a set of instructions to be
executed repeatedly until a certain condition is true or false.
 Switch can test only equality whereas if.. Can evaluate any type
of relational or logical expression.  As per placing of condition to be tested, a loop may be
 In switch a single value or constant can be tested but in if.. more Entry-controlled or Exit-controlled loop. In Entry controlled
versatile expression can be tested. loop, a condition is tested (pre test) before executing the
statements. Whereas in Exit-controlled statements are
 The switch statement can handle only byte, short, int or char
variable but If.. can test more data type like float, double or executed first then condition is tested (post test), which
string etc. ensures at least on time execution of statements.
switch (exp 1)
if ( condition 1)
{ case <cont>:switch (exp2)
 As per number of execution, a loop may be Counter-
{ switch (exp1) controlled or Sentinel loop. Counter controlled loops are
{ …….
{ …….
……. executed fixed number of times, but sentinel loop may be
…….
} stopped any time by giving its sentinel value. i.e. number of
}
} ………… execution can not be forecasted.
else }  A body of loop contains a block, having statements to be
{ …….; executed.
} Nesting of switch with switch or if.. may be used….

The for .. loop Variations in for.. loop


In simple use, a for.. Loop is Entry-controlled and counter  Multiple initialization and update expression
controlled loop having fixed number of iteration. A for.. Loop may contain multiple initialization and/or update
expressions separated by (,)
for (initialization exp (s) ; condition ; update exp (s) ) for (i=0,sum=0;i<=n; sum++, i++)
{ ………..  Optional Expressions
……….. In for loop initialization, condition and update section may be
Looping statements omitted. Note that (;) must be present.
}
for ( ; i<=n ; )

for (int i=1; i<=10 ; i++ ) { //loop to find even nos. up to 50  Infinite loop
System.out.println (“”+i); for (int i=0; i<=50 ; i=i+2) For.. Loop may be endless (infinite) when defined condition is
always true or it is omitted.
} System.out.println (“”+i); for ( ; ; )
 Empty loop
//loop to find factorial //loop to get sum of first 10 nos. for.. Loop may not contain any statement in looping body i.e.
int fact=1,num=5; int sum=0; Empty loop. If (;) placed after for.. Loop then empty loop is
for (int i=1; i<=10 ; i++ ) { created.
for (int i=1; i<=num ; i++)
sum=sum+ i; for (int i=1; i<=300 ; i++) ;
fact=fact * i; }  Variable declared inside for.. Loop can’t accessed outside the loop.
System.out.println (“factorial=”+fact); System.out.println (“”+sum); Since it is out of scope.

The while.. loop The do..while loop


In simple use, a while .. Loop is Entry-controlled and counter Unlike for.. and while.. Loop, do..while loop is Exit-controlled and counter
controlled or sentinel looping statement, which executes controlled or sentinel looping statement, which executes statements
until defined condition is true. It always executes at least once.
statements until defined condition is true.
while (condition) do
{ ……….. { ………..
……….. ……….. Looping statements
Looping statements
} } while (condition);

//while loop to find factorial // do.. Loop to print A – Z letters //do.. loop fixed time
int fact=1,num=5,i=1; char ch =‘A’; int i=1;
int i=1;
while (i<=num) do { do
while ( i<=10) {
{ fact=fact * i; System.out.println (“”+i); {System.out.println (“”+i);
i=i+1;
i++; ch++; i++;
System.out.println (“”+i);
} } while (ch<=‘Z’); } while (i<=10);
} System.out.println (“factorial=”+fact);

A while loop also may be empty or infinite A do…while loop also may be empty or infinite

Visit "http://ip4you.blogspot.in" for more... 14


Chapter 3: JAVA GUI Prog.-Review (XII-IP)

Which loop is better ? Jump statements in Java


 Java offers three looping statements i.e. for..,  Java offers three jump statements (return, break and
continue), which transfers the control else where
while.. and do..while. There are some situation unconditionally.
where one loop is more appropriate than  The return statement can be used any where in the
others. program. It transfers the control to calling module or
 The for loop is best suited where number of Operating System. However Java provides System.exit()
execution is known in advance. (fixed method to stop the execution of program.
execution)  The break is used with for.., while, do.. and switch
 The while and do.. are more suitable in the statements which enables the program to skip over some
part of the code and places control just after the nearest
situations where it is not known that when closing of block. It is used to terminate the loop.
loop will terminate. (unpredictable times of
 The continue statement is used within looping statement
execution). (not with switch) and works like break i.e. it also skips the
 The do.. Loop ensures at least one time of statements. Unlike break, it forces the next iteration of loop
execution since it is Exit-controlled loop. by skipping the in between code and continues the loop.

Break and Continue the loop Scope of a variable


While (condition 1) for (ini;cond;update) Do  In Java, a variable can be declared any where in the program but
{ statement 1; { statement 1; { statement 1; before using them.
if (condition 2) if (condition) if (condition)  The area of program within which a variable is accessible, known
break; break; break; as its scope.
……. ……. …….
statement 2; statement 2; statement 2;  A variable can be accessed within the block where it is declared.
} } } While (test condition)
Statement 3; Statement 3; Statement 3; { int x=10; Scope of x
if (a>b)
{ int y=5;
While (condition 1) for (ini;cond;update) Do Scope of y
…………
{ statement 1; { statement 1; { statement 1; }
if (condition 2) if (condition) if (condition) else Scope of z
continue; continue; continue; { int z=3;
……. ……. ……. …….
statement 2; Y and z are not
statement 2; statement 2; }
} accessible here
} } While (test condition) ……….
Statement 3; Statement 3; Statement 3; }

Visit "http://ip4you.blogspot.in" for more... 15

You might also like