Java Notes
Java Notes
Class are a blueprint or a set of instructions to build a specific type of object. It is a basic concept of Object-Oriented
Programming which revolve around the real-life entities. Class in Java determines how an object will behave and
what the object will contain.
Syntax
class <class_name>{
field;
method;
}
Object is an instance of a class. An object in OOPS is nothing but a self-contained component which consists of
methods and properties to make a particular type of data useful. For example color name, table, bag, barking. When
you send a message to an object, you are asking the object to invoke or execute one of its methods as defined in the
class.
From a programming point of view, an object in OOPS can include a data structure, a variable, or a function. It has a
memory location allocated. Java Objects are designed as class hierarchies.
Syntax
A Class in object oriented programming is a blueprint or prototype that defines the variables and the methods
(functions) common to all Java Objects of a certain kind.
An object in OOPS is a specimen of a class. Software objects are often used to model real-world objects you find in
everyday life.
Class - Dogs
Data members or objects- size, age, color, breed, etc.
Methods- eat, sleep, sit and run.
Summary:
Java Class is an entity that determines how Java Objects will behave and what objects will contain
A Java object is a self-contained component which consists of methods and properties to make certain type
of data useful
A class system allows the program to define a new class (derived class) in terms of an existing class
(superclass) by using a technique like inheritance, overriding and augmenting.
1
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created.
At the time of calling constructor, memory for the object is allocated in the memory.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a
default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to
write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.
Overriding and Overloading are two very important concepts in Java. They are confusing for Java novice
programmers. This post illustrates their differences by using two simple examples.
1. Definitions
Overloading occurs when two or more methods in one class have the same method name but different parameters.
Overriding means having two methods with the same method name and parameters (i.e., method signature). One of
the methods is in the parent class and the other is in the child class. Overriding allows a child class to provide a
specific implementation of a method that is already provided its parent class.
1). The real object type in the run-time, not the reference variable's type, determines which overridden method is
used at runtime. In contrast, reference type determines which overloaded method will be used at compile time.
2
2). Polymorphism applies to overriding, not to overloading.
3). Overriding is a run-time concept while overloading is a compile-time concept.
3. An Example of Overriding
Here is an example of overriding. After reading the code, guess the output.
class Dog{
public void bark(){
[Link]("woof ");
}
}
class Hound extends Dog{
public void sniff(){
[Link]("sniff ");
}
bowl
In the example above, the dog variable is declared to be a Dog. During compile time, the compiler checks if
the Dog class has the bark() method. As long as the Dog class has the bark() method, the code compilers. At run-
time, a Hound is created and assigned to dog. The JVM knows that dog is referring to the object of Hound, so it calls
the bark() method of Hound. This is called Dynamic Polymorphism.
4. An Example of Overloading
class Dog{
public void bark(){
[Link]("woof ");
}
//overloading method
public void bark(int num){
for(int i=0; i<num; i++)
[Link]("woof ");
}
}
In this overloading example, the two bark method can be invoked by using different parameters. Compiler know
they are different because they have different method signature (method name and method parameter list).
3
Access Modifiers in Java
1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside
the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package through
child class. If you do not make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here, we
are going to learn the access modifiers only.
Access Modifier within class within package outside package by subclass only outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
4
In this example, we have created two classes A and Simple. A class contains private data member and private
method. We are accessing these private members from outside the class, so there is a compile-time error.
class A{
private int data=40;
private void msg(){[Link]("Hello java");}
}
If you make any class constructor private, you cannot create the instance of that class from outside the class. For
example:
class A{
private A(){}//private constructor
void msg(){[Link]("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within
package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more
restrictive than protected, and public.
In this example, we have created two packages pack and mypack. We are accessing the A class from outside its
package, since A class is not public, so it cannot be accessed from outside the package.
package pack;
class A{
void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
5
A obj = new A();//Compile Time Error
[Link]();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package but through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the
class.
In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can
be accessed from outside the package. But msg method of this package is declared as protected, so it can be
accessed from outside the class only through inheritance.
/save by [Link]
package pack;
public class A{
protected void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
}
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
1.
package pack;
public class A{
6
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Output:Hello
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object.
It is an important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you
inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
7
Terms used in Inheritance
o Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class,
extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also
called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and
methods of the existing class when you create a new class. You can use the same fields and methods
already defined in the previous class.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship
between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000
8
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about
interfaces later.
When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class
inherits the Animal class, so there is the single inheritance.
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}
barking...
eating...
9
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given
below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel
inheritance.
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}}
Output:
weeping...
barking...
eating
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given
below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}}
Output:
meowing...
eating...
10
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes
have the same method and you call it from child class object, there will be ambiguity to call the method of A or B
class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So
whether you have same method or different, there will be compile time error.
class A{
void msg(){[Link]("Hello");}
}
class B{
void msg(){[Link]("Welcome");}
}
class C extends A,B{//suppose if it were
Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by
inheritance.
Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from another
class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in
different ways.
For example, think of a superclass called Animal that has a method called animalSound(). Subclasses of Animals
could be Pigs, Cats, Dogs, Birds - And they also have their own implementation of an animal sound (the pig oinks,
and the cat meows, etc.):
class Animal {
public void animalSound() {
[Link]("The animal makes a sound");
11
}
}
Remember from the Inheritance chapter that we use the extends keyword to inherit from a class.
Now we can create Pig and Dog objects and call the animalSound() method on both of them:
Example
class Animal {
public void animalSound() {
[Link]("The animal makes a sound");
}
}
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
[Link]();
[Link]();
[Link]();
}
}
12
What is Swing in Java?
Swing in Java is a Graphical User Interface (GUI) toolkit that includes the GUI components. Swing provides a rich
set of widgets and packages to make sophisticated GUI components for Java applications. Swing is a part of Java
Foundation Classes(JFC), which is an API for Java programs that provide GUI.
The Java Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older, platform dependent
GUI toolkit. You can use the Java GUI programming components like button, textbox, etc. from the library and do
not have to create the components from scratch.
13
Java Swing class Hierarchy Diagram
All components in Java Swing are JComponent which can be added to container classes.
Container classes are classes that can have other components on it. So for creating a Java GUI, we need at least one
container object. There are 3 types of Java Swing containers.
1. Panel: It is a pure container and is not a window in itself. The sole purpose of a Panel is to organize the
components on to a window.
2. Frame: It is a fully functioning window with its title and icons.
3. Dialog: It can be thought of like a pop-up window that pops out when a message has to be displayed. It is
not a fully functioning window like the Frame.
GUI (Graphical User Interface) in Java is an easy-to-use visual experience builder for Java applications. It is
mainly made of graphical components like buttons, labels, windows, etc. through which the user can interact with an
application. GUI plays an important role to build easy interfaces for Java applications.
import [Link].*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](300,300);
JButton button = new JButton("Press");
[Link]().add(button); // Adds Button to content pane of frame
14
[Link](true);
}
}
import [Link].*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](300,300);
JButton button1 = new JButton("Press");
[Link]().add(button1);
[Link](true);
}
}
Step 5) How about adding two buttons? Copy the following code into an editor.
import [Link].*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](300,300);
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
[Link]().add(button1);
[Link]().add(button2);
[Link](true);
}
}
15
The Layout manager is used to layout (or arrange) the GUI java components inside a [Link] are many
layout managers, but the most frequently used are-
Java BorderLayout
A BorderLayout places components in up to five areas: top, bottom, left, right, and center. It is the default layout
manager for every java JFrame
Java FlowLayout
FlowLayout is the default layout manager for every JPanel. It simply lays out components in a single row one after
the other.
Java GridBagLayout
It is the more sophisticated of all layouts. It aligns components by placing them within a grid of cells, allowing
components to span more than one cell.
16
Try to code yourself before looking at the program below.
17
[Link]().add([Link], ta);
[Link](true);
}
}
Java JOptionPane
The JOptionPane class is used to provide standard dialog boxes such as message dialog box, confirm dialog box and
input dialog box. These dialog boxes are used to display information or get input from the user. The JOptionPane
class inherits JComponent class.
JOptionPane(Object message, int It is used to create an instance of JOptionPane to display a message with specified
messageType message type and default options.
JDialog createDialog(String title) It is used to create and return a new parentless JDialog
with the specified title.
static void showMessageDialog(Component parentComponent, It is used to create a message dialog with given title and
18
Object message, String title, int messageType) messageType.
static int showConfirmDialog(Component parentComponent, It is used to create a dialog with the options Yes, No and
Object message) Cancel; with the title, Select an Option.
void setInputValue(Object newValue) It is used to set the input value that was selected or input
by the user.
import [Link].*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
[Link](f,"Hello, Welcome to Javatpoint.");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
Output:
import [Link].*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
[Link](f,"Successfully Updated.","Alert",JOptionPane.WARNING_MESSAGE);
}
public static void main(String[] args) {
new OptionPaneExample();
}
19
}
Output:
import [Link].*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
String name=[Link](f,"Enter Name");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
Output:
import [Link].*;
import [Link].*;
public class OptionPaneExample extends WindowAdapter{
JFrame f;
OptionPaneExample(){
f=new JFrame();
[Link](this);
[Link](300, 300);
[Link](null);
[Link](JFrame.DO_NOTHING_ON_CLOSE);
[Link](true);
}
public void windowClosing(WindowEvent e) {
20
int a=[Link](f,"Are you sure?");
if(a==JOptionPane.YES_OPTION){
[Link](JFrame.EXIT_ON_CLOSE);
}
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
Output:
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a single line of read
only text. The text can be changed by an application but a user cannot edit it directly. It inherits JComponent class.
JLabel() Creates a JLabel instance with no image and with an empty string for the
title.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and horizontal
horizontalAlignment) alignment.
21
Commonly used Methods:
Methods Description
void setText(String text) It defines the single line of text this component will display.
void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents along the X axis.
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the X axis.
import [Link].*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
[Link](50,50, 100,30);
l2=new JLabel("Second Label.");
[Link](50,100, 100,30);
[Link](l1); [Link](l2);
[Link](300,300);
[Link](null);
[Link](true);
}
}
Output:
22
Java JLabel Example with ActionListener
import [Link].*;
import [Link].*;
import [Link].*;
public class LabelExample extends Frame implements ActionListener{
JTextField tf; JLabel l; JButton b;
LabelExample(){
tf=new JTextField();
[Link](50,50, 150,20);
l=new JLabel();
[Link](50,100, 250,20);
b=new JButton("Find IP");
[Link](50,150,95,30);
[Link](this);
add(b);add(tf);add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try{
String host=[Link]();
String ip=[Link](host).getHostAddress();
[Link]("IP of "+host+" is: "+ip);
}catch(Exception ex){[Link](ex);}
}
public static void main(String[] args) {
new LabelExample();
}}
Output:
Java JTextField
The object of a JTextField class is a text component that allows the editing of a single line text. It inherits
JTextComponent class.
23
Commonly used Constructors:
Constructor Description
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int columns) Creates a new TextField initialized with the specified text and columns.
JTextField(int columns) Creates a new empty TextField with the specified number of columns.
void addActionListener(ActionListener l) It is used to add the specified action listener to receive action events from this
textfield.
Action getAction() It returns the currently set Action for this ActionEvent source, or null if no
Action is set.
void removeActionListener(ActionListener It is used to remove the specified action listener so that it no longer receives
l) action events from this textfield.
import [Link].*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
[Link](50,100, 200,30);
t2=new JTextField("AWT Tutorial");
[Link](50,150, 200,30);
24
[Link](t1); [Link](t2);
[Link](400,400);
[Link](null);
[Link](true);
}
}
Output:
import [Link].*;
import [Link].*;
public class TextFieldExample implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample(){
JFrame f= new JFrame();
tf1=new JTextField();
[Link](50,50,150,20);
tf2=new JTextField();
[Link](50,100,150,20);
tf3=new JTextField();
[Link](50,150,150,20);
[Link](false);
b1=new JButton("+");
[Link](50,200,50,50);
b2=new JButton("-");
[Link](120,200,50,50);
[Link](this);
[Link](this);
[Link](tf1);[Link](tf2);[Link](tf3);[Link](b1);[Link](b2);
[Link](300,300);
[Link](null);
[Link](true);
}
public void actionPerformed(ActionEvent e) {
String s1=[Link]();
String s2=[Link]();
int a=[Link](s1);
int b=[Link](s2);
int c=0;
if([Link]()==b1){
c=a+b;
}else if([Link]()==b2){
25
c=a-b;
}
String result=[Link](c);
[Link](result);
}
public static void main(String[] args) {
new TextFieldExample();
}}
Output:
Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the editing of multiple line text. It
inherits JTextComponent class
JTextArea(int row, int column) Creates a text area with the specified number of rows and columns that displays no
text initially.
JTextArea(String s, int row, int Creates a text area with the specified number of rows and columns that displays
column) specified text.
26
Commonly used Methods:
Methods Description
void insert(String s, int position) It is used to insert the specified text on the specified position.
void append(String s) It is used to append the given text to the end of the document.
import [Link].*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
[Link](10,30, 200,200);
[Link](area);
[Link](300,300);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new TextAreaExample();
}}
Output:
27
import [Link].*;
import [Link].*;
public class TextAreaExample implements ActionListener{
JLabel l1,l2;
JTextArea area;
JButton b;
TextAreaExample() {
JFrame f= new JFrame();
l1=new JLabel();
[Link](50,25,100,30);
l2=new JLabel();
[Link](160,25,100,30);
area=new JTextArea();
[Link](20,75,250,200);
b=new JButton("Count Words");
[Link](100,300,120,30);
[Link](this);
[Link](l1);[Link](l2);[Link](area);[Link](b);
[Link](450,450);
[Link](null);
[Link](true);
}
public void actionPerformed(ActionEvent e){
String text=[Link]();
String words[]=[Link]("\\s");
[Link]("Words: "+[Link]);
[Link]("Characters: "+[Link]());
}
public static void main(String[] args) {
new TextAreaExample();
}
}
Output:
Java JButton
The JButton class is used to create a labeled button that has platform independent implementation. The application
result in some action when the button is pushed. It inherits AbstractButton class.
28
1. public class JButton extends AbstractButton implements Accessible
import [Link].*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
[Link](50,100,95,30);
[Link](b);
[Link](400,400);
29
[Link](null);
[Link](true);
}
}
Output:
import [Link].*;
import [Link].*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
[Link](50,50, 150,20);
JButton b=new JButton("Click Here");
[Link](50,100,95,30);
[Link](new ActionListener(){
public void actionPerformed(ActionEvent e){
[Link]("Welcome to Javatpoint.");
}
});
[Link](b);[Link](tf);
[Link](400,400);
[Link](null);
[Link](true);
}
}
Output:
30
Example of displaying image on the button:
import [Link].*;
public class ButtonExample{
ButtonExample(){
JFrame f=new JFrame("Button Example");
JButton b=new JButton(new ImageIcon("D:\\[Link]"));
[Link](100,100,100, 40);
[Link](b);
[Link](300,400);
[Link](null);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ButtonExample();
}
}
Output:
Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false). Clicking on a
CheckBox changes its state from "on" to "off" or from "off" to "on ".It inherits JToggleButton class.
JJCheckBox() Creates an initially unselected check box button with no text, no icon.
31
JChechBox(String s) Creates an initially unselected check box with text.
JCheckBox(String text, boolean selected) Creates a check box with text and specifies whether or not it is initially selected.
JCheckBox(Action a) Creates a check box where properties are taken from the Action supplied.
AccessibleContext getAccessibleContext() It is used to get the AccessibleContext associated with this JCheckBox.
import [Link].*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
[Link](100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
[Link](100,150, 50,50);
[Link](checkBox1);
[Link](checkBox2);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
Output:
32
Java JCheckBox Example with ItemListener
import [Link].*;
import [Link].*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
final JLabel label = new JLabel();
[Link]([Link]);
[Link](400,100);
JCheckBox checkbox1 = new JCheckBox("C++");
[Link](150,100, 50,50);
JCheckBox checkbox2 = new JCheckBox("Java");
[Link](150,150, 50,50);
[Link](checkbox1); [Link](checkbox2); [Link](label);
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
[Link]("C++ Checkbox: "
+ ([Link]()==1?"checked":"unchecked"));
}
});
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
[Link]("Java Checkbox: "
+ ([Link]()==1?"checked":"unchecked"));
}
});
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}
Output:
33
Java JCheckBox Example: Food Order
import [Link].*;
import [Link].*;
public class CheckBoxExample extends JFrame implements ActionListener{
JLabel l;
JCheckBox cb1,cb2,cb3;
JButton b;
CheckBoxExample(){
l=new JLabel("Food Ordering System");
[Link](50,50,300,20);
cb1=new JCheckBox("Pizza @ 100");
[Link](100,100,150,20);
cb2=new JCheckBox("Burger @ 30");
[Link](100,150,150,20);
cb3=new JCheckBox("Tea @ 10");
[Link](100,200,150,20);
b=new JButton("Order");
[Link](100,250,80,30);
[Link](this);
add(l);add(cb1);add(cb2);add(cb3);add(b);
setSize(400,400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
float amount=0;
String msg="";
if([Link]()){
amount+=100;
msg="Pizza: 100\n";
}
if([Link]()){
amount+=30;
msg+="Burger: 30\n";
}
if([Link]()){
amount+=10;
msg+="Tea: 10\n";
34
}
msg+="-----------------\n";
[Link](this,msg+"Total: "+amount);
}
public static void main(String[] args) {
new CheckBoxExample();
}
}
Output:
Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user is shown on the top of
a menu. It inherits JComponent class.
1. public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, ActionListener, Acce
ssible
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified array.
JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in the specified Vector.
35
Commonly used Methods:
Methods Description
void removeAllItems() It is used to remove all the items from the list.
import [Link].*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
[Link](50, 50,90,20);
[Link](cb);
[Link](null);
[Link](400,500);
[Link](true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
Output:
36
Java JComboBox Example with ActionListener
import [Link].*;
import [Link].*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
final JLabel label = new JLabel();
[Link]([Link]);
[Link](400,100);
JButton b=new JButton("Show");
[Link](200,100,75,20);
String languages[]={"C","C++","C#","Java","PHP"};
final JComboBox cb=new JComboBox(languages);
[Link](50, 100,90,20);
[Link](cb); [Link](label); [Link](b);
[Link](null);
[Link](350,350);
[Link](true);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "
+ [Link]([Link]());
[Link](data);
}
});
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
Output:
37
Java JList
The object of JList class represents a list of text items. The list of text items can be set up so that the user can choose
either one item or multiple items. It inherits JComponent class.
JList(ary[] listData) Creates a JList that displays the elements in the specified array.
JList(ListModel<ary> dataModel) Creates a JList that displays elements from the specified, non-null, model.
Void addListSelectionListener(ListSelectionListener It is used to add a listener to the list, to be notified each time a
listener) change to the selection occurs.
38
ListModel getModel() It is used to return the data model that holds a list of items
displayed by the JList component.
void setListData(Object[] listData) It is used to create a read-only ListModel from an array of objects.
import [Link].*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
[Link]("Item1");
[Link]("Item2");
[Link]("Item3");
[Link]("Item4");
JList<String> list = new JList<>(l1);
[Link](100,100, 75,75);
[Link](list);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new ListExample();
}}
Output:
39
final JLabel label = new JLabel();
[Link](500,100);
JButton b=new JButton("Show");
[Link](200,150,80,30);
final DefaultListModel<String> l1 = new DefaultListModel<>();
[Link]("C");
[Link]("C++");
[Link]("Java");
[Link]("PHP");
final JList<String> list1 = new JList<>(l1);
[Link](100,100, 75,75);
DefaultListModel<String> l2 = new DefaultListModel<>();
[Link]("Turbo C++");
[Link]("Struts");
[Link]("Spring");
[Link]("YII");
final JList<String> list2 = new JList<>(l2);
[Link](100,200, 75,75);
[Link](list1); [Link](list2); [Link](b); [Link](label);
[Link](450,450);
[Link](null);
[Link](true);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "";
if ([Link]() != -1) {
data = "Programming language Selected: " + [Link]();
[Link](data);
}
if([Link]() != -1){
data += ", FrameWork Selected: ";
for(Object frame :[Link]()){
data += frame + " ";
}
}
[Link](data);
}
});
}
public static void main(String args[])
{
new ListExample();
}}
Output:
40
Java JPanel
The JPanel is a simplest container class. It provides space in which an application can attach any other component. It
inherits the JComponents class.
JPanel() It is used to create a new JPanel with a double buffer and a flow layout.
JPanel(boolean isDoubleBuffered) It is used to create a new JPanel with FlowLayout and the specified buffering strategy.
JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout manager.
import [Link].*;
import [Link].*;
public class PanelExample {
PanelExample()
{
JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
[Link](40,80,200,200);
[Link]([Link]);
JButton b1=new JButton("Button 1");
41
[Link](50,100,80,30);
[Link]([Link]);
JButton b2=new JButton("Button 2");
[Link](100,100,80,30);
[Link]([Link]);
[Link](b1); [Link](b2);
[Link](panel);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new PanelExample();
}
}
Output:
42