Lecture 1: Java Features
This handout is a
traditional introduction to any language features. You might not be able to
comprehend some of the features fully at this stage but don’t worry, you’ll get
to know about these as we move on with the course.
1.1
Design Goals of Java
The massive growth of
the Internet and the World-Wide Web leads us to a completely new way of looking
at development of software that can run on different platforms like Windows,
Linux and Solaris etc.
1.1.1
Right Language, Right Time
•
Java
came on the scene in 1995 to immediate popularity.
•
Before
that, C and C++ dominated the software development
o compiled,
no robust memory model, no garbage collector causes memory leakages, not
great support of built in libraries
•
Java
brings together a great set of "programmer efficient" features
o
Putting
more work on the CPU to make things easier for the programmer.
1.1.2
Java - Buzzwords (Vocabulary)
• From
the original Sun Java whitepaper: "Java is a simple, object-oriented,
distributed, interpreted, robust, secure, architecture-neutral, portable,
high-performance, multi-threaded, and dynamic language."
•
Here
are some original java buzzwords.
1.1.3
Java -- Language + Libraries
•
Java
has two parts.
o
The core language -- variables, arrays,
objects
The Java Virtual Machine (JVM)
runs the core language
The core language is simple enough to
run on small devices phones, smart cards, PDAs.
o
The
libraries
Java includes a large collection of
standard library classes to provide "off the shelf" code. (Useful
built-in classes that comes with the language to perform basic tasks)
Example of these classes is String,
ArrayList, HashMap, StringTokenizer (to break string into substrings), Date ...
Java programmers are
more productive in part because they have access to a large set of standard,
well documented library classes.
1.1.4
Simple
•
Very
similar C/C++ syntax, operators, etc.
• The
core language is simpler than C++ -- no operator overloading, no pointers, no
multiple inheritance
•
The
way a java program deals with memory is much simpler than C or C++.
1.1.5
Object-Oriented
•
Java
is fundamentally based on the OOP notions of classes and objects.
•
Java uses a formal OOP type system that
must be obeyed at compile-time and run-time.
• This
is helpful for larger projects, where the structure helps keep the various
parts consistent. Contrast to Perl, which has a more anything-goes feel.
1.1.6
Distributed / Network Oriented
• Java
is network friendly -- both in its portable, threaded nature, and because
Common networking operations are built-in to the Java libraries.
1.1.7
Robust / Secure / Safe
•
Java
is very robust
o Both, vs.
unintentional errors and vs. malicious code such as viruses.
o
Java has slightly worse performance
since it does all this checking. (Or put the other way, C can be faster since
it doesn't check anything.)
• The
JVM "verifier" checks the code when it is loaded to verify that it
has the correct Structure -- that it does not use an uninitialized pointer, or
mix int and pointer types. This is one-time "static" analysis --
checking that the code has the correct structure without running it.
• The
JVM also does "dynamic" checking at runtime for certain operations,
such as pointer and array access, to make sure they are touching only the
memory they should. You will write code that runs into
• As
a result, many common bugs and security problems (e.g. "buffer
overflow") are not possible in java. The checks also make it easier to
find many common bugs easy, since they are caught by the runtime checker.
• You
will generally never write code that fails the verifier, since your compiler is
smart enough to only generate correct code. You will write code that runs into
the runtime checks all the time as you debug -- array out of bounds, null
pointer.
• Java
also has a runtime Security Manager can check which operations a particular
piece of code is allowed to do. As a result, java can run untrusted code in a
"sandbox" where, for example, it can draw to the screen but cannot
access the local file system.
1.1.8
Portable
•
"Write
Once Run Anywhere", and for the most part this works.
• Not
even a recompile is required -- a Java executable can work, without change, on
any Java enabled platform.
1.1.9
Support for Web and Enterprise Web Applications
• Java
provides an extensive support for the development of web and enterprise
applications
• Servlets,
JSP, Applets, JDBC, RMI, EJBs and JSF etc. are some of the Java technologies
that can be used for the above mentioned purposes.
1.1.10
High-performance
•
The
first versions of java were pretty slow.
• Java
performance has gotten a lot better with aggressive just-in-time-compiler (JIT)
techniques.
• Java
performance is now similar to C -- a little slower in some cases, faster in a
few cases. However memory use and startup time are both worse than C.
• Java
performance gets better each year as the JVM gets smarter. This works, because
making the JVM smarter does not require any great change to the java language,
source code, etc.
1.1.11
Multi-Threaded
•
Java
has a notion of concurrency wired right in to the language itself.
• This
works out more cleanly than languages where concurrency is bolted on after the
fact.
1.1.12
Dynamic
• Class
and type information is kept around at runtime. This enables runtime loading
and inspection of code in a very flexible way.
1.1.13
Java Compiler Structure
• The
source code for each class is in a .java file. Compile each class to produce
“.class” file.
•
Sometimes, multiple .class files are
packaged together into a .zip or .jar "archive" file.
• On
UNIX or windows, the java compiler is called "javac". To compile all
the .java files in a directory use "javac *.java".
1.1.14 Java:
Programmer Efficiency
• Faster Development
o Building
an application in Java takes about 50% less time than in C or C++. So, Faster
time to market
o
Java is said to be “Programmer
Efficient”.
•
OOP
o
Java is thoroughly OOP language with
robust memory system
o
Memory errors largely disappear because
of the safe pointers and garbage collector. The lack of memory errors accounts
for much of the increased programmer productivity.
•
Libraries
o
Code re-uses at last -- String,
ArrayList, Date, available and documented in a standard way
1.1.15 Microsoft vs.
Java
• Microsoft
hates Java, since a Java program (portable) is not tied to any particular
operating system. If Java is popular, then programs written in Java might
promote non-Microsoft operating systems. For basically the same reason, all the
non-Microsoft vendors think Java is a great idea.
• Microsoft's
C# is very similar to Java, but with some improvements, and some questionable
features added in, and it is not portable in the way Java is. Generally it is
considered that C# will be successful in the way that Visual Basic is: a nice
tool to build Microsoft only software.
• Microsoft
has used its power to try to derail Java somewhat, but Java remains very
popular on its merits.
1.1.16
Java Is For Real
• Java
has a lot of hype, but much of it is deserved. Java is very well matched for
many modern problem
• Using
more memory and CPU time but less programmer time is an increasingly appealing
tradeoff.
•
Robustness and portability can be very
useful features
•
A
general belief is that Java is going to stay here for the next 10-20 years
Lecture 2: Java Virtual Machine
& Runtime Environment
2.1
Basic Concept
When you write a
program in C++ it is known as source code. The C++ compiler converts this
source code into the machine code of underlying system (e.g. Windows) If you
want to run that code on Linux you need to recompile it with a Linux based
compiler. Due to the difference in compilers, sometimes you need to modify your
code.
Java has introduced the
concept of WORA (write once run anywhere). When you write a java program it is
known as the source code of java. The java compiler does not compile this source
code for any underlying hardware system, rather it compiles it for a software
system known as JVM (This compiled code is known as byte code). We have
different JVMs for different systems (such as JVM for Windows, JVM for Linux
etc). When we run our program the JVM interprets (translates) the compiled
program into the language understood by the underlying system. So we write our
code once and the JVM runs it everywhere according to the underlying system.
This concept is discussed in detail
below
2.1.1
Byte code
•
Java
programs (Source code) are compiled into a form called Java bytecodes.
• The
Java compiler reads Java language source (.java) files, translates the source
into Java bytecodes, and places the bytecodes into class (.class) files.
•
The
compiler generates one class file for each class contained in java source file.
2.1.2
Java Virtual Machine (JVM)
•
The
central part of java platform is java virtual machine.
•
Java bytecode executes by special
software known as a "virtual machine".
• Most
programming languages compile source code directly into machine code, suitable
for execution
•
The difference with Java is that it uses
bytecode - a special type of machine code.
The
JVM executes Java bytecodes, so Java bytecodes can be thought of as the machine
language of the JVM.
•
JVM
are available for almost all operating systems.
• Java
byte code is executed by using any operating system’s JVM. Thus achieve
portability.
2.1.3
Java Runtime Environment (JRE)
• The
Java Virtual Machine is a part of a large system i.e. Java Runtime Environment
(JRE).
•
Each operating system and CPU
architecture requires different JRE.
•
The JRE consists of set of built-in
classes, as well as a JVM.
• Without
an available JRE for a given environment, it is impossible to run Java
software.
2.2
Java Program Development and Execution Steps
Java program normally go through five
phases. These are
•
Edit,
•
Compile,
•
Load,
•
Verify and
•
Execute
We
look over all the above mentioned phases in a bit detail. First consider the
following figure that summarizes the all phases of a java program.
2.2.1 Phase 1: Edit
Phase 1 consists of editing a file. This
is accomplished with an editor program. The programmer types a java program
using the editor like notepad, and make corrections if necessary.
When the programmer specifies that the
file in the editor should be saved, the program is stored on a secondary
storage device such as a disk. Java program file name ends with a .java
extension.
On Windows platform, notepad is a simple
and commonly used editor for the beginners. However java integrated development
environments (IDEs) such as NetBeans, Borland JBuilder, JCreator and IBM’s
Eclipse Java built-in editors that are smoothly integrated into the programming
environment.
2.2.2 Phase 2: Compile
In Phase 2, the programmer gives the
command javac to compile the program. The java compiler translates the java
program into byte codes, which is the language understood by the java
interpreter.
To compile a program called Welcome.java
type javac Welcome.java at the command window of your system. If the
program compiles correctly, a file called Welcome. Class is produced. This is
the file containing the byte codes that will be interpreted during the
execution phase.
2.2.3 Phase 3:
Loading
In phase 3, the program must first be
placed in memory before it can be executed. This is done by the class loader,
which takes the .class file (or files) containing the byte codes and transfers
it to memory. The .class file can be loaded from a disk on your system or over
a network (such as your local university or company network or even the
internet).
Applications
|
(Programs)
|
are loaded into memory and
executed using
|
the
|
java interpreter
|
via the
command java. When executing a Java application called Welcome, the command
|
||||
Java Welcome
|
||||
Invokes the
|
interpreter
|
for the Welcome application and
causes the
|
class
|
loader
to load
|
information used
in the Welcome program.
2.2.4 Phase 4:
Verify
Before the byte codes in an application
are executed by the java interpreter, they are verified by the byte code
verifier in Phase 4. This ensures that the byte codes for class that are
loaded form the internet (referred to as downloaded classes) are
valid and that they do not violate Java’s security restrictions. Java enforces
strong security because java programs arriving over the network should
not be able to cause damage to your
files and your system (as computer viruses might).
2.2.5 Phase 5: Execute
2.3
Installation and Environment Setting
2.3.1
Installation
• Download
the latest version j2se5.0 (java 2 standard edition) from http://java.sun.com or get it from any other
source like CD.
•
Note:
j2se also called jdk (java development kit). You can also use the previous
versions like jdk 1.4 or 1.3 etc. but it is recommended that you use either
jdk1.4 or jdk5.0
•
Install
j2se5.0 on your system
Note: For the rest of this handout,
assume that j2se is installed in C:\Program Files\Java\jdk1.5.0
2.3.2 Environment Setting
Once
you successfully installed the j2se, the next step is environment or path
setting. You can accomplish this in either of two ways.
2.3.2.1 Temporary Path Setting
• Open the command prompt from Start Programs
Accessories Command Prompt.
The command prompt
screen would be opened in front of you.
• Write the command on the command prompt
according to the following format
path = < java
installation directory\bin >
• So, according to handout, the command
will look like this
path = C:\Program
Files\Java\jdk1.5.0\bin
• To Test whether path has been set or
not, write javac and press ENTER. If the
list
of options displayed as shown in the below figure means that you have
successfully completed the steps of path setting.
The above procedure is illustrates
in the given below picture.
Note: The issue with
the temporary path setting is you have to repeat the above explained procedure
again and again each time you open a new command prompt window. To avoid this
overhead, it is better to set your path permanently
2.3.2.2
Permanent Path Setting
•
In
Windows NT (XP, 2000), you can set the permanent environment variable.
•
Right
click on my computer icon click on properties as shown below
A System
Properties frame would appear as shown in the picture.
•
Select the
|
advanced tab
followed by clicking
the Environment Variable
|
button. The
|
Environment
variables frame would be displayed in front of you
|
• Locate
the Path variable in the System or user variables, if it is present there,
select it by single click. Press Edit button. The following dialog box would be
appeared.
• Write; C:\Program
Files\Java\jdk1.5.0\bin at the end of the value
field.
Press
OK button. Remember to write semicolon (;) before writing the path for java
installation directory as illustrated in the above figure.
• If
Path variable does not exist, click the New button. Write variable name “PATH”,
variable value C:\Program Files\Java\jdk1.5.0\bin and press OK button.
• Now
open the command prompt and write javac, press enter button. You see the
list of options would be displayed.
• After
setting the path permanently, you have no need to set the path for each new
opened command prompt.
2.4
First Program in Java
Like any other
programming language, the java programming language is used to create
applications. So, we start from building a classical “Hello World” application,
which is generally used as the first program for learning any new language.
2.4.1
|
HelloWorldApp
|
•
|
Open notepad editor from
Start ProgarmFiles Accessories Notepad.
|
•
|
Write the following code into
it.
|
Note:
Don’t
copy paste the given below code. Probably it gives errors and you can’t able to
remove them at the beginning stage.
public class HelloWorldApp
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
•
To
save your program, move to File menu and choose save as option.
• Save
your program as “HelloWorldApp.java” in some directory. Make sure to add
double quotes around class name while saving your program. For this example
create a folder known as “examples” in D: drive
Note: Name
of file must match the name of the public class in the file (at line 4). Moreover,
it is case sensitive. For example, if your class name is MyClasS, than file
name must be MyClasS. Otherwise the Java compiler will refuse to compile the
program.
For the rest of this handout, we assume
that program is saved in D:\examples directory.
2.4.2
HelloWorldApp Described
•
Lines 1-3
o
Like
in C++, You can add multiple line comments that are ignored by the compiler.
•
Lines 4
o
Line 4 declares the class name as HelloWorldApp.
In java, every line of code must reside inside class. This is also the name of
our program (HelloWorldApp.java).The compiler creates the HelloWorldApp.class
if this program successfully gets compiled.
•
Lines 5
o
Line 5 is where the program execution
starts. The java interpreter must find this defined exactly as given or it will
refuse to run the program. (However you can change the name of parameter that
is passed to main. i.e. you can write String[] argv or String[] someParam
instead of String[] args)
o
Other programming languages, notably C++
also use the main() declaration as the starting point for
execution. However the main function in C++ is global and resides outside of
all classes where as in Java the main function must reside inside a class. In
java there are no global variables or functions. The various parts of this main
function declaration will be covered at the end of this handout.
•
Lines 6
o
Again like C++, you can also add single
line comment
•
Lines 7
o
Line 7 illustrates the method call. The println()
method is used to print something on the console. In this example println()
method takes a string argument and writes it to the standard output i.e.
console.
•
Lines 8-9
o
Line 8-9 of the program, the two braces,
close the method main() and the classHelloWorldApp
respectively.
2.4.3 Compiling
and Running HelloWorldApp
• Open
the command prompt
from Start Program
Files Accessories. OR
alternatively you can write
cmd in the run command window.
• Write
cd.. to came out from any folder, and cd [folder name] to move inside the
specified directory. To move from one drive to another, use [Drive Letter]: See
figure given below
• After
reaching to the folder or directory that contains your source code, in our case
HelloWorldApp.java.
•
Use “javac” on the command line to
compile the source file ( “.java” file).
D:\examples>
javac HelloWorld.java
• If
program gets successfully compiled, it will create a new file in the same
directory named HelloWorldApp.class that contains the byte-code.
• Use
“java” on the command line to run the compiled .class file. Note “.class” would
be added with the file name.
•
D:\examples> java HelloWorld
• You
can see the Hello World would be printed on the console. Hurrah! You are
successful in writing, compiling and executing your first program in java
2.4.4
Points to Remember
•
Recompile
the class after making any changes
•
Save your program before compilation
• Only
run that class using java command that contains the main method, because
program executions always starts form main
2.5
An Idiom Explained
•
You
will see the following line of code often:
o
public
static void main(String args[]) { …}
•
About
main()
o
“main”
is the function from which your program starts
o
Why public?
o
Since main method is called by the JVM
that is why it is kept public so that it is accessible from outside. Remember
private methods are only accessible from within the class
•
Why
static?
o
Every Java program starts when the JRE
(Java Run Time Environment) calls themain method of that
program. If main is not static then the JRE have to create an object of the
class in which main method is present and call the main method on that object
(In OOP based languages method are called using the name of object if they are
not static). It is made static so that the JRE can call it without creating an
object.
o
Also
to ensure that there is only one copy of the main method per class
•
Why
void?
o
Indicates that main ( ) does not return
anything.
•
What
is String args[] ?
o
Way of specifying input (often called
command-line arguments) at startup of application. More on it latter
Lecture 3: Learning Basics
3.1
Strings
A
string is commonly considered to be a sequence of characters stored in
memory and accessible as a unit. Strings in java are represented as objects.
3.1.1
String Concatenation
•
“+”
operator is used to concatenate strings
o
System.out.println(“Hello”
+ “World”) will print Hello World on console
• String
concatenated with any other data type such as int will also convert that
datatype to String and the result will be a concatenated String displayed on
console. For example,
o
int
i = 4;
o int j = 5;
System.out.println (“Hello” +
i);// will print Hello 4 on screen
o However
System.out.println(i+j);//will
print 9 on the console because both i and j are of type int.
3.1.2 Comparing Strings
For comparing Strings never use
== operator, use equals method of String class.
• ==
operator compares addresses (shallow comparison) while equals compares values
(deep comparison)
o E.g.
string1.equals(string2)
Example Code: String concatenation and
comparison
public class StringTest {
Setting the close button operation for the
frame in Java
Making a Frame Non Resizable in Java
Removing the title bar of the Frame in Java
Create a Container in Java awt
Changing the Cursor in Java
Image on Frame in Java AWT
Event handling in Java AWT
Item Events in Java
Simple Form in Java
Item Events in Java
How to Create Button on Frame
How to create CheckBox On frame
Choice Option (Combo) In Java
BorderLayout Example In java
Radio Button In Java
TextArea Frame in Java
Image Demo
Image Size
import java.awt.*;
public class AwtSetIconOfFrame{
public static void main(String[] args){
Frame frame = new Frame("Icon setting for the Awt Frame");
Image icon = Toolkit.getDefaultToolkit().getImage("icon_confused.gif");
Label lbl = new Label("Welcome in Roseindia.net Tutorial.",Label.CENTER);
frame.add(lbl);
frame.setSize(400,400);
frame.setIconImage(icon);
frame.setVisible(true);
}
}
public class AwtSetIconOfFrame{
public static void main(String[] args){
Frame frame = new Frame("Icon setting for the Awt Frame");
Image icon = Toolkit.getDefaultToolkit().getImage("icon_confused.gif");
Label lbl = new Label("Welcome in Roseindia.net Tutorial.",Label.CENTER);
frame.add(lbl);
frame.setSize(400,400);
frame.setIconImage(icon);
frame.setVisible(true);
}
}
Setting the close button operation for the
frame in Java
import java.awt.*;
import java.awt.event.*;
public class AwtCloseButtonEvent{
public static void main(String[] args){
Frame frame = new Frame("Close Operation Frame");
Label lbl = new Label("Welcom in Roseindia.net Tutorial",Label.CENTER);
frame.add(lbl);
frame.setSize(400,400);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
}
import java.awt.event.*;
public class AwtCloseButtonEvent{
public static void main(String[] args){
Frame frame = new Frame("Close Operation Frame");
Label lbl = new Label("Welcom in Roseindia.net Tutorial",Label.CENTER);
frame.add(lbl);
frame.setSize(400,400);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
}
Making a Frame Non Resizable in Java
import java.awt.*;
import java.awt.event.*;
public class AwtFrameNonResizable{
public static void main(String[] args){
Frame frame = new Frame("Non Resizable Frame");
Image icon = Toolkit.getDefaultToolkit().getImage("icon_confused.gif");
frame.setIconImage(icon);
Label lbl = new Label("Welcome in Roseindia.net Tutorial.",Label.CENTER);
frame.add(lbl);
frame.setResizable(false);
frame.setSize(400,400);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
Frame frame = (Frame)we.getSource();
frame.dispose();
}
});
}
}
import java.awt.event.*;
public class AwtFrameNonResizable{
public static void main(String[] args){
Frame frame = new Frame("Non Resizable Frame");
Image icon = Toolkit.getDefaultToolkit().getImage("icon_confused.gif");
frame.setIconImage(icon);
Label lbl = new Label("Welcome in Roseindia.net Tutorial.",Label.CENTER);
frame.add(lbl);
frame.setResizable(false);
frame.setSize(400,400);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
Frame frame = (Frame)we.getSource();
frame.dispose();
}
});
}
}
Removing the title bar of the Frame in Java
import java.awt.*;
import java.awt.event.*;
public class AwtWithoutTitleFrame{
public static void main(String[] args){
Frame frame = new Frame("Without Title Bar Frame");
Label lbl = new Label("Welcome in Roseindia.net Tutorial.",Label.CENTER);
frame.setUndecorated(true);
frame.add(lbl);
frame.setSize(400,400);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
Frame frame = (Frame)we.getSource();
frame.dispose();
}
});
}
}
import java.awt.event.*;
public class AwtWithoutTitleFrame{
public static void main(String[] args){
Frame frame = new Frame("Without Title Bar Frame");
Label lbl = new Label("Welcome in Roseindia.net Tutorial.",Label.CENTER);
frame.setUndecorated(true);
frame.add(lbl);
frame.setSize(400,400);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
Frame frame = (Frame)we.getSource();
frame.dispose();
}
});
}
}
Create a Container in Java awt
import java.awt.*;
import java.awt.event.*;
public class CreateContainer{
public static void main(String[] args){
Panel panel = new Panel();
panel.add(new Button("Button 1"));
panel.add(new Button("Button 2"));
panel.add(new Button("Button 3"));
Frame frame = new Frame("Container Frame");
TextArea txtArea = new TextArea();
frame.add(txtArea, BorderLayout.CENTER);
frame.add(panel, BorderLayout.SOUTH);
frame.setSize(400,400);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
}
import java.awt.event.*;
public class CreateContainer{
public static void main(String[] args){
Panel panel = new Panel();
panel.add(new Button("Button 1"));
panel.add(new Button("Button 2"));
panel.add(new Button("Button 3"));
Frame frame = new Frame("Container Frame");
TextArea txtArea = new TextArea();
frame.add(txtArea, BorderLayout.CENTER);
frame.add(panel, BorderLayout.SOUTH);
frame.setSize(400,400);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
}
Changing the Cursor in Java
import java.awt.*;
import java.awt.event.*;
public class ChangeCursor{
public static void main(String[] args) {
Frame f = new Frame("Change cursor");
Panel panel = new Panel();
Button comp1 = new Button("Ok");
Button comp2 = new Button("Cancel");
panel.add(comp1);
panel.add(comp2);
f.add(panel,BorderLayout.CENTER);
f.setSize(200,200);
f.setVisible(true);
Cursor cur = comp1.getCursor();
Cursor cur1 = comp2.getCursor();
comp1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
comp2.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
}
import java.awt.event.*;
public class ChangeCursor{
public static void main(String[] args) {
Frame f = new Frame("Change cursor");
Panel panel = new Panel();
Button comp1 = new Button("Ok");
Button comp2 = new Button("Cancel");
panel.add(comp1);
panel.add(comp2);
f.add(panel,BorderLayout.CENTER);
f.setSize(200,200);
f.setVisible(true);
Cursor cur = comp1.getCursor();
Cursor cur1 = comp2.getCursor();
comp1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
comp2.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
}
Image on Frame in Java AWT
import java.awt.*;
import java.awt.event.*;
public class AwtImage extends Frame{
Image img;
public static void main(String[] args){
AwtImage ai = new AwtImage();
}
public AwtImage(){
super("Image Frame");
MediaTracker mt = new MediaTracker(this);
img = Toolkit.getDefaultToolkit().getImage("icon_confused.gif");
mt.addImage(img,0);
setSize(400,400);
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
dispose();
}
});
}
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g){
if(img != null)
g.drawImage(img, 100, 100, this);
else
g.clearRect(0, 0, getSize().width, getSize().height);
}
}
import java.awt.event.*;
public class AwtImage extends Frame{
Image img;
public static void main(String[] args){
AwtImage ai = new AwtImage();
}
public AwtImage(){
super("Image Frame");
MediaTracker mt = new MediaTracker(this);
img = Toolkit.getDefaultToolkit().getImage("icon_confused.gif");
mt.addImage(img,0);
setSize(400,400);
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
dispose();
}
});
}
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g){
if(img != null)
g.drawImage(img, 100, 100, this);
else
g.clearRect(0, 0, getSize().width, getSize().height);
}
}
Event handling in Java AWT
import java.awt.*;
import java.awt.event.*;
public class AwtEvent extends Frame implements ActionListener{
Label lbl;
public static void main(String argv[]){
AwtEvent t = new AwtEvent();
}
public AwtEvent(){
super("Event in Java awt");
setLayout(new BorderLayout());
try{
Button button = new Button("INSERT_AN_URL_HERE");
button.addActionListener(this);
add(button, BorderLayout.NORTH);
Button button1 = new Button("INSERT_A_FILENAME_HERE");
button1.addActionListener(this);
add(button1, BorderLayout.SOUTH);
lbl = new Label("Roseindia.net");
add(lbl, BorderLayout.CENTER);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
catch (Exception e){}
setSize(400,400);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
Button bt = (Button)e.getSource();
String str = bt.getLabel();
lbl.setText(str);
}
}
import java.awt.event.*;
public class AwtEvent extends Frame implements ActionListener{
Label lbl;
public static void main(String argv[]){
AwtEvent t = new AwtEvent();
}
public AwtEvent(){
super("Event in Java awt");
setLayout(new BorderLayout());
try{
Button button = new Button("INSERT_AN_URL_HERE");
button.addActionListener(this);
add(button, BorderLayout.NORTH);
Button button1 = new Button("INSERT_A_FILENAME_HERE");
button1.addActionListener(this);
add(button1, BorderLayout.SOUTH);
lbl = new Label("Roseindia.net");
add(lbl, BorderLayout.CENTER);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
catch (Exception e){}
setSize(400,400);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
Button bt = (Button)e.getSource();
String str = bt.getLabel();
lbl.setText(str);
}
}
Item Events in Java
import java.awt.*;
import java.awt.event.*;
public class AwtItemEvent extends Frame{
TextArea txtArea;
public AwtItemEvent(String title){
super(title);
txtArea = new TextArea();
add(txtArea, BorderLayout.CENTER);
Choice choice = new Choice();
choice.addItem("red");
choice.addItem("green");
choice.addItem("blue");
choice.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
txtArea.setText("This is the " + e.getItem() + " color.\n");
}
});
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
add(choice, BorderLayout.NORTH);
setSize(400,400);
setVisible(true);
setResizable(false);
}
public static void main(String[] args){
AwtItemEvent f = new AwtItemEvent("AWT Demo");
}
}
import java.awt.event.*;
public class AwtItemEvent extends Frame{
TextArea txtArea;
public AwtItemEvent(String title){
super(title);
txtArea = new TextArea();
add(txtArea, BorderLayout.CENTER);
Choice choice = new Choice();
choice.addItem("red");
choice.addItem("green");
choice.addItem("blue");
choice.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
txtArea.setText("This is the " + e.getItem() + " color.\n");
}
});
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
add(choice, BorderLayout.NORTH);
setSize(400,400);
setVisible(true);
setResizable(false);
}
public static void main(String[] args){
AwtItemEvent f = new AwtItemEvent("AWT Demo");
}
}
Simple Form in Java
import java.awt.*;
import java.awt.event.*;
public class DataEntry {
public static void main(String[] args) {
Frame frm=new Frame("DataEntry frame");
Label lbl = new Label("Please fill this blank:");
frm.add(lbl);
frm.setSize(350,200);
frm.setVisible(true);
frm.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
Panel p = new Panel();
Panel p1 = new Panel();
Label jFirstName = new Label("First Name");
TextField lFirstName = new TextField(20);
Label jLastName =new Label("Last Name");
TextField lLastName=new TextField(20);
p.setLayout(new GridLayout(3,1));
p.add(jFirstName);
p.add(lFirstName);
p.add(jLastName);
p.add(lLastName);
Button Submit=new Button("Submit");
p.add(Submit);
p1.add(p);
frm.add(p1,BorderLayout.NORTH);
}
}
import java.awt.event.*;
public class DataEntry {
public static void main(String[] args) {
Frame frm=new Frame("DataEntry frame");
Label lbl = new Label("Please fill this blank:");
frm.add(lbl);
frm.setSize(350,200);
frm.setVisible(true);
frm.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
Panel p = new Panel();
Panel p1 = new Panel();
Label jFirstName = new Label("First Name");
TextField lFirstName = new TextField(20);
Label jLastName =new Label("Last Name");
TextField lLastName=new TextField(20);
p.setLayout(new GridLayout(3,1));
p.add(jFirstName);
p.add(lFirstName);
p.add(jLastName);
p.add(lLastName);
Button Submit=new Button("Submit");
p.add(Submit);
p1.add(p);
frm.add(p1,BorderLayout.NORTH);
}
}
Item Events in Java
import java.awt.*;
import java.awt.event.*;
public class AwtItemEvent extends Frame{
TextArea txtArea;
public AwtItemEvent(String title){
super(title);
txtArea = new TextArea();
add(txtArea, BorderLayout.CENTER);
Choice choice = new Choice();
choice.addItem("red");
choice.addItem("green");
choice.addItem("blue");
choice.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
txtArea.setText("This is the " + e.getItem() + " color.\n");
}
});
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
add(choice, BorderLayout.NORTH);
setSize(400,400);
setVisible(true);
setResizable(false);
}
public static void main(String[] args){
AwtItemEvent f = new AwtItemEvent("AWT Demo");
}
}
import java.awt.event.*;
public class AwtItemEvent extends Frame{
TextArea txtArea;
public AwtItemEvent(String title){
super(title);
txtArea = new TextArea();
add(txtArea, BorderLayout.CENTER);
Choice choice = new Choice();
choice.addItem("red");
choice.addItem("green");
choice.addItem("blue");
choice.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
txtArea.setText("This is the " + e.getItem() + " color.\n");
}
});
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
add(choice, BorderLayout.NORTH);
setSize(400,400);
setVisible(true);
setResizable(false);
}
public static void main(String[] args){
AwtItemEvent f = new AwtItemEvent("AWT Demo");
}
}
How to Create Button on Frame
import java.awt.*;
import java.awt.event.*;
public class ButtonText {
public static void main(String[] args) {
Frame frame=new Frame("Button Frame");
Button button = new Button("Submit");
frame.add(button);
frame.setLayout(new FlowLayout());
frame.setSize(200,100);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
import java.awt.event.*;
public class ButtonText {
public static void main(String[] args) {
Frame frame=new Frame("Button Frame");
Button button = new Button("Submit");
frame.add(button);
frame.setLayout(new FlowLayout());
frame.setSize(200,100);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
How to create CheckBox On frame
import java.awt.*;
import java.awt.event.*;
public class CheckBoxDemo{
public static void main(String[] args){
Frame frame= new Frame("Checkbox");
Checkbox check=new Checkbox("Welcome");
Checkbox check1=new Checkbox("YOu");
frame.add(check);
frame.add(check1);
frame.setLayout(new FlowLayout());
frame.setSize(300,200);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
import java.awt.event.*;
public class CheckBoxDemo{
public static void main(String[] args){
Frame frame= new Frame("Checkbox");
Checkbox check=new Checkbox("Welcome");
Checkbox check1=new Checkbox("YOu");
frame.add(check);
frame.add(check1);
frame.setLayout(new FlowLayout());
frame.setSize(300,200);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
Choice Option (Combo) In Java
import java.awt.*;
import java.awt.event.*;
public class ChoiceOptionExample{
public static void main(String[] args) {
Frame frame=new Frame("Choice");
Label label=new Label("What is your Choice:");
Choice choice=new Choice();
frame.add(label);
frame.add(choice);
choice.add("ROSE");
choice.add("INDIA");
choice.add("WELCOME");
frame.setLayout(new FlowLayout());
frame.setSize(250,150);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
import java.awt.event.*;
public class ChoiceOptionExample{
public static void main(String[] args) {
Frame frame=new Frame("Choice");
Label label=new Label("What is your Choice:");
Choice choice=new Choice();
frame.add(label);
frame.add(choice);
choice.add("ROSE");
choice.add("INDIA");
choice.add("WELCOME");
frame.setLayout(new FlowLayout());
frame.setSize(250,150);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
BorderLayout Example In java
import java.awt.*;
import java.awt.event.*;
public class BorderLayoutExample {
public static void main(String[] args) {
Frame frame= new Frame("BorderLayout Frame");
Panel pa= new Panel();
Button ba1= new Button();
Button ba2=new Button();
Button ba3=new Button();
Button ba4=new Button();
Button ba5=new Button();
frame.add(pa);
pa.setLayout(new BorderLayout());
pa.add(new Button("Wel"), BorderLayout.NORTH);
pa.add(new Button("Come"), BorderLayout.SOUTH);
pa.add(new Button("Rose"), BorderLayout.EAST);
pa.add(new Button("India"), BorderLayout.WEST);
pa.add(new Button("RoseIndia"), BorderLayout.CENTER);
frame.setSize(300,300);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
import java.awt.event.*;
public class BorderLayoutExample {
public static void main(String[] args) {
Frame frame= new Frame("BorderLayout Frame");
Panel pa= new Panel();
Button ba1= new Button();
Button ba2=new Button();
Button ba3=new Button();
Button ba4=new Button();
Button ba5=new Button();
frame.add(pa);
pa.setLayout(new BorderLayout());
pa.add(new Button("Wel"), BorderLayout.NORTH);
pa.add(new Button("Come"), BorderLayout.SOUTH);
pa.add(new Button("Rose"), BorderLayout.EAST);
pa.add(new Button("India"), BorderLayout.WEST);
pa.add(new Button("RoseIndia"), BorderLayout.CENTER);
frame.setSize(300,300);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
Radio Button In Java
import java.awt.*;
import java.awt.event.*;
public class RadioButton{
public static void main(String[] args) {
Frame fm=new Frame("RedioButton Group");
Label la=new Label("What is your choice:");
fm.setLayout(new GridLayout(0, 1));
CheckboxGroup cg1=new CheckboxGroup();
fm.add(la);
fm.add(new Checkbox("MATH", cg1, true));
fm.add(new Checkbox("PHYSICS", cg1, false));
fm.add(new Checkbox("CHEMISTRY", cg1, false));
fm.add(new Checkbox("ENGLISH", cg1, false));
fm.setSize(250,200);
fm.setVisible(true);
fm.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
}
import java.awt.event.*;
public class RadioButton{
public static void main(String[] args) {
Frame fm=new Frame("RedioButton Group");
Label la=new Label("What is your choice:");
fm.setLayout(new GridLayout(0, 1));
CheckboxGroup cg1=new CheckboxGroup();
fm.add(la);
fm.add(new Checkbox("MATH", cg1, true));
fm.add(new Checkbox("PHYSICS", cg1, false));
fm.add(new Checkbox("CHEMISTRY", cg1, false));
fm.add(new Checkbox("ENGLISH", cg1, false));
fm.setSize(250,200);
fm.setVisible(true);
fm.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
}
TextArea Frame in Java
import java.awt.*;
import java.awt.event.*;
public class TextAreaFrame{
public static void main(String[] args) {
Frame frame=new Frame("Text Frame");
TextArea textArea=new TextArea("Welcome Roseindia",10,20);
frame.add(textArea);
frame.setLayout(new FlowLayout());
frame.setSize(250,250);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
import java.awt.event.*;
public class TextAreaFrame{
public static void main(String[] args) {
Frame frame=new Frame("Text Frame");
TextArea textArea=new TextArea("Welcome Roseindia",10,20);
frame.add(textArea);
frame.setLayout(new FlowLayout());
frame.setSize(250,250);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
Image Demo
import java.awt.*;
import java.awt.event.*;
public class ImageDemo extends Frame{
Image image;
public static void main(String[] args) {
new ImageDemo();
}
public ImageDemo(){
setTitle("Image Demo Example!");
setSize(300,200);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
setVisible(true);
}
public void paint(Graphics g){
Toolkit tool = Toolkit.getDefaultToolkit();
image = tool.getImage("bt_home.gif");
g.drawString("Image 1:",20,40);
g.drawImage(image,20,45,this);
image = tool.getImage("icon_mini_search.gif");
g.drawString("Image 2:",20,80);
g.drawImage(image,20,90,this);
image = tool.getImage("apache_pb2_ani.gif");
g.drawString("Image 3:",20,130);
g.drawImage(image,20,150,this);
}
}
import java.awt.event.*;
public class ImageDemo extends Frame{
Image image;
public static void main(String[] args) {
new ImageDemo();
}
public ImageDemo(){
setTitle("Image Demo Example!");
setSize(300,200);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
setVisible(true);
}
public void paint(Graphics g){
Toolkit tool = Toolkit.getDefaultToolkit();
image = tool.getImage("bt_home.gif");
g.drawString("Image 1:",20,40);
g.drawImage(image,20,45,this);
image = tool.getImage("icon_mini_search.gif");
g.drawString("Image 2:",20,80);
g.drawImage(image,20,90,this);
image = tool.getImage("apache_pb2_ani.gif");
g.drawString("Image 3:",20,130);
g.drawImage(image,20,150,this);
}
}
Image Size
import java.awt.*;
import java.awt.event.*;
public class ImageSize extends Frame{
Image image;
public static void main(String[] args) {
try{
new ImageSize();
}
catch(InterruptedException e){}
}
public ImageSize() throws InterruptedException{
Toolkit tool = Toolkit.getDefaultToolkit();
image = tool.getImage("1.gif");
MediaTracker mTracker = new MediaTracker(this);
mTracker.addImage(image,1);
mTracker.waitForID(1);
int width = image.getWidth(null);
int height = image.getHeight(null);
System.out.println("The width of image: " + width);
System.out.println("The height of image: " + height);
setSize(width, height);
setTitle("Image Size Example!");
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
setVisible(true);
}
public void paint(Graphics g){
g.drawImage(image,0,0,null);
}
}
import java.awt.event.*;
public class ImageSize extends Frame{
Image image;
public static void main(String[] args) {
try{
new ImageSize();
}
catch(InterruptedException e){}
}
public ImageSize() throws InterruptedException{
Toolkit tool = Toolkit.getDefaultToolkit();
image = tool.getImage("1.gif");
MediaTracker mTracker = new MediaTracker(this);
mTracker.addImage(image,1);
mTracker.waitForID(1);
int width = image.getWidth(null);
int height = image.getHeight(null);
System.out.println("The width of image: " + width);
System.out.println("The height of image: " + height);
setSize(width, height);
setTitle("Image Size Example!");
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
setVisible(true);
}
public void paint(Graphics g){
g.drawImage(image,0,0,null);
}
}
No comments:
Post a Comment