1. 1 | P a g e
EX: 1 // HELLO WORLD
class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
Output of program:
EX:2 // If else in Java code
import java.util.Scanner;
class IfElse {
public static void main(String[] args) {
int marksObtained, passingMarks;
passingMarks = 40;
Scanner input = new
Scanner(System.in);
System.out.println("Input marks scored
by you");
marksObtained = input.nextInt();
if (marksObtained >= passingMarks) {
System.out.println("You passed the
exam.");
}
else {
System.out.println("Unfortunately you
failed to pass the exam.");
}
}
}
Output of program:
EX:3 // Nested If else in Java code
import java.util.Scanner;
class NestedIfElse {
public static void main(String[] args) {
int marksObtained, passingMarks;
char grade;
passingMarks = 40;
Scanner input = new
Scanner(System.in);
System.out.println("Input marks scored
by you");
2. 2 | P a g e
marksObtained = input.nextInt();
if (marksObtained >= passingMarks) {
if (marksObtained > 90)
grade = 'A';
else if (marksObtained > 75)
grade = 'B';
else if (marksObtained > 60)
grade = 'C';
else
grade = 'D';
System.out.println("You passed the
exam and your grade is " + grade);
}
else {
grade = 'F';
System.out.println("You failed and your
grade is " + grade);
}
}
}
Java for loop syntax
for (/* Initialization of variables */ ;
/*Conditions to test*/ ; /* Increment(s) or
decrement(s) of variables */)
{
// Statements to execute i.e. Body of for
loop
}
Ex:4 // Infinite for loop
for (;;) {
System.out.println("Java programmer");
}
Ex: 5 program below uses for loop to
print first 10 natural numbers i.e. from 1
to 10.
//Java for loop program
class ForLoop {
public static void main(String[] args) {
int c;
for (c = 1; c <= 10; c++) {
System.out.println(c);
}
}
}
Output of program:
Ex:6Java for loop example to print stars in
console
Following star pattern is printed
*
**
***
****
*****
class Stars {
public static void main(String[] args) {
int row, numberOfStars;
for (row = 1; row <= 10; row++) {
3. 3 | P a g e
for(numberOfStars = 1; numberOfStars
<= row; numberOfStars++) {
System.out.print("*");
}
System.out.println(); // Go to next line
}
}
}
Output of program:
JAVA WHILE LOOP
while loop syntax:
while (condition(s))
{
// Body of loop
}
1. If the condition holds true then the
body of loop is executed, after execution
of loop body condition is tested again
and if the condition is true then body of
loop is executed again and the process
repeats until condition becomes false.
Condition is always evaluated to true or
false and if it is a constant, For example
while (c) { …} where c is a constant then
any non zero value of c is considered
true and zero is considered false.
2. You can test multiple conditions such
as
while ( a > b && c != 0) {
// Loop body
}
Loop body is executed till value of a is
greater than value of b and c is not
equal to zero.
3. Body of loop can contain more than
one statement. For multiple statements
you need to place them in a block using
{} and if body of loop contain only single
statement you can optionally use {}. It is
recommended to use braces always to
make your program easily readable and
understandable.
EX: 7 program asks the user to input an
integer and prints it until user enter 0
(zero).
import java.util.Scanner;
class WhileLoop {
public static void main(String[] args) {
int n;
Scanner input = new
Scanner(System.in);
System.out.println("Input an integer");
while ((n = input.nextInt()) != 0) {
System.out.println("You entered " + n);
System.out.println("Input an integer");
}
System.out.println("Out of loop");
}
}
4. 4 | P a g e
Output of program:
Ex:8 // Printing alphabets
class Alphabets
{
public static void main(String args[])
{
char ch;
for( ch = 'a' ; ch <= 'z' ; ch++ )
System.out.println(ch);
}
}
You can easily modify the above java
program to print alphabets in upper
case.output of program:
Printing alphabets using while loop (only
body of main method is shown):
char c = 'a';
while (c <= 'z') {
System.out.println(c);
c++;
}
Using do while loop:
char c = 'A';
do {
System.out.println(c);
c++;
} while (c <= 'Z');
Ex: 9 // program for multiplication table
import java.util.Scanner;
class MultiplicationTable
{
public static void main(String args[])
{
int n, c;
System.out.println("Enter an integer to
print it's multiplication table");
Scanner in = new Scanner(System.in);
n = in.nextInt();
System.out.println("Multiplication
table of "+n+" is :-");
for ( c = 1 ; c <= 10 ; c++ )
System.out.println(n+"*"+c+" =
"+(n*c));
}
}
5. 5 | P a g e
Output of program:
Retrieving input from the user
Scanner a = new Scanner(System.in);
Here Scanner is the class name, a is the
name of object, new keyword is used to
allocate the memory and System.in is
the input stream. Following methods of
Scanner class are used in the program
below :-
1) nextInt to input an integer
2) nextFloat to input a float
3) nextLine to input a string
Ex:10
import java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string
"+s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered
integer "+a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float
"+b);
}
}
Output of program:
Ex:11
import java.util.Scanner;
class AddNumbers
{
public static void main(String args[])
{
int x, y, z;
System.out.println("Enter two integers
to calculate their sum ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
z = x + y;
System.out.println("Sum of entered
integers = "+z);
}
}
6. 6 | P a g e
Output of program:
Ex:12
import java.util.Scanner;
class OddOrEven
{
public static void main(String args[])
{
int x;
System.out.println("Enter an integer to
check if it is odd or even ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
if ( x % 2 == 0 )
System.out.println("You entered an
even number.");
else
System.out.println("You entered an
odd number.");
}
}
Output of program:
Ex:13 Another method to check odd or
even
import java.util.Scanner;
class EvenOdd
{
public static void main(String args[])
{
int c;
System.out.println("Input an integer");
Scanner in = new Scanner(System.in);
c = in.nextInt();
if ( (c/2)*2 == c )
System.out.println("Even");
else
System.out.println("Odd");
}
}
EX:15 //Fahrenheit to Celsius
import java.util.*;
class FahrenheitToCelsius {
public static void main(String[] args) {
float temperatue;
Scanner in = new Scanner(System.in);
System.out.println("Enter temperatue in
Fahrenheit");
temperatue = in.nextInt();
temperatue = ((temperatue - 32)*5)/9;
System.out.println("Temperatue in
Celsius = " + temperatue);
}
}
7. 7 | P a g e
Output of program:
[ For Celsius to Fahrenheit conversion
use
T = 9*T/5 + 32
where T is temperature on Celsius
scale.]
** Create and test Fahrenheit to Celsius
program yourself for practice.
Java methods
Java program consists of one or more
classes and a class may contain
method(s).
A class can do very little without
methods.
A method has a name and return type.
Main method is a must in a Java
program as execution begins from it.
Syntax of methods
"Access specifier" "Keyword(s)" "return
type" methodName(List of arguments)
{
// Body of method
}
Access specifier can be public or private
which decides whether other classes can
call a method.
Keywords are used for some special
methods such as static or synchronized.
Return type indicate return value which
method returns.
Method name is a valid Java identifier
name.
Access specifier, Keyword and
arguments are optional.
Examples of methods declaration:
public static void main(String[] args);
void myMethod();
private int maximum();
public synchronized int
search(java.lang.Object);
Ex:16
class Methods
{
// Constructor method
Methods()
{
System.out.println("Constructor method
is called when an object of it's class is
created");
}
// Main method where program
execution begins
public static void main(String[] args)
{
staticMethod();
Methods object = new Methods();
object.nonStaticMethod();
}
// Static method
static void staticMethod()
{
System.out.println("Static method can be
called without creating object");
8. 8 | P a g e
}
// Non static method
void nonStaticMethod()
{
System.out.println("Non static method
must be called by creating an object");
}
}
Output of program:
Java methods list
Java has a built in library of many useful
classes and there are thousands of
methods which can be used in your
programs.
javap package.classname
For example
javap java.lang.String // list all methods
and constants of String class.
javap java.math.BigInteger // list
constants and methods of BigInteger
class in java.math package
Java String methods
String class contains methods which are
useful for performing operations on
String(s). Below program illustrate how
to use inbuilt methods of String class.
Java string class program
EX:15
class StringMethods
{
public static void main(String args[])
{
int n;
String s = "Java programming", t = "", u =
"";
System.out.println(s);
// Find length of string
n = s.length();
System.out.println("Number of
characters = " + n);
// Replace characters in string
t = s.replace("Java", "C++");
System.out.println(s);
System.out.println(t);
// Concatenating string with another
string
u = s.concat(" is fun");
System.out.println(s);
System.out.println(u);
}
}
Output of program:
Ex:16 Array input at run time
import java.io.*;
import java.util.Scanner;
class arrayruntime
{
public static void main(String args[])
{
Scanner a =new Scanner(System.in);
int a1[] = new int[5];
int j= a1.length;
9. 9 | P a g e
for(int i=0;i<j;i++)
{
int k= a.nextInt();
a1[i]=k;
}
for(int i=0;i<j;i++)
{
System.out.println(a1[i]);
}
}
}
Output
Java arrayruntime
45
45
57
35
29
45
45
57
35
29
Ex:17 Sorting odd and even
import java.io.*;
import java.util.Scanner;
class arrayruntimeoddeven
{
public static void main(String args[])
{
Scanner a =new Scanner(System.in);
int a1[] = new int[5];
int j= a1.length;
for(int i=0;i<j;i++)
{
int k= a.nextInt();
a1[i]=k;
}
System.out.println("The array is");
for(int i=0;i<j;i++)
{
System.out.println(a1[i]);
}
for(int i=0;i<j;i++)
{
if(a1[i]%2==0)
{
int l = a1[i];
System.out.println(l+" is even");
}
else
{
int l = a1[i];
System.out.println(l+" is odd");
}
}
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>java
arrayruntimeoddeven
23
33
54
32
78
The array is
23
33
54
32
78
23 is odd
33 is odd
54 is even
32 is even
78 is even
10. 10 | P a g e
Ex:18 Constructor
class area
{
int length;
int breadth;
area ( int a, int b)//constructor
{
length =a;
breadth =b;
}
int rectarea()
{
int area2 =length*breadth;
return area2;
}
}
class constructor
{
public static void main(String args[])
{
int area1;
area a1 = new area(12,15);
//a1.getdata(12,15);
area1 = a1.rectarea();
System.out.println("area is "+area1);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>java
constructor
area is 180
Ex:19 getinput during execution
class get
{
public static void main(String args[])
{
int a= Integer.parseInt(args[0]);
System.out.println(a);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>java get 2
2
Ex:20 Get user input at runtime using
bufferedreader
import java.io.*;
public class getuserinput
{
public static void main (String[] args)
{
System.out.print("Enter your name and
press Enter: ");
BufferedReader br = new
BufferedReader(new
InputStreamReader(System.in));
String name = null;
try
{
name = br.readLine();
}
catch (IOException e)
{
System.out.println("Error!");
System.exit(1);
}
System.out.println("Your name is " +
name);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
getuserinput.java
C:Program
FilesJavajdk1.6.0_13bin>java
getuserinput
Enter your name and press Enter:
sudharsun
Your name is sudharsun
11. 11 | P a g e
Ex:21 Inheritance
class Room
{
int length;
int breadth;
Room (int x,int y)
{
length =x;
breadth=y;
}
}
class BedRoom extends Room
{
int height;
BedRoom(int x,int y, int z)
{
super(x,y);
height =z;
}
int volume()
{
return(length*breadth*height);
}
}
class inheritance
{
public static void main(String args[])
{
BedRoom r1= new BedRoom(2,4,5);
int vol = r1.volume();
System.out.println(vol);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
inheritance.java
C:Program
FilesJavajdk1.6.0_13bin>java
inheritance
40
Ex:22 Get input using data input stream
import java .io.DataInputStream;
class input
{
public static void main(String args[])
{
DataInputStream in = new
DataInputStream(System.in);
int i=0;
try
{
i=Integer.parseInt(in.readLine());
}
catch (Exception e)
{
}
System.out.println(i);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>java input
23
23
Ex:23 Overloading
class area
{
int length;
int breadth;
area(int x,int y) /*using constructor*/
{
length= x;
breadth= y;
}
area(int x) /*using constructor*/
{
length=breadth=x;
}
int area1()
{
return(length*breadth);
}
12. 12 | P a g e
}
class overload
{
public static void main(String args[])
{
area r1 = new area(2,3);/*calling
Constructor*/
area r2 = new area(3);
int a1 = r1.area1();
int a2 = r2.area1();
System.out.println(a1);
System.out.println(a2);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
overload.java
C:Program
FilesJavajdk1.6.0_13bin>java overload
6
9
Ex:24 Overload program 2 input at
runtime
class room
{
int length;
int breadth;
room(int x,int y)
{
length= x;
breadth= y;
}
room(int x)
{
length=breadth=x;
}
int area()
{
return(length*breadth);
}
}
class overload1
{
public static void main(String args[])
{
int i= Integer.parseInt(args[0]);
int j= Integer.parseInt(args[1]);
room r1 = new room(i,j);
int k= Integer.parseInt(args[2]);
room r2 = new room(k);
int area1 = r1.area();
int area2 = r2.area();
System.out.println(area1);
System.out.println(area2);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>java overload1
101 101 12
10201
144
Ex:25 Overriding
class superclass
{
int x;
superclass(int x)
{
this.x=x;
}
void display()
{
System.out.println(x);
}
}
class subclass extends superclass
{
int y;
subclass(int x , int y)
{
super(x);
this.y=y;
}
void display()
{
13. 13 | P a g e
System.out.println(y);
}
}
class overriding
{
public static void main(String args[])
{
subclass s1=new subclass(100,200);
s1.display();
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
overriding.java
C:Program
FilesJavajdk1.6.0_13bin>java overriding
200
Ex:26 Replace a letter in a word
class replace
{
public static void main(String args[])
{
String s1= "Hello";
System.out.println(s1);
String s2 = s1.replaceFirst("lo","p");
System.out.println(s2);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>java replace
Hello
Help
Ex:27 Sample program for java
class area
{
int length;//
int breadth;//Field Decl
void getdata( int a, int b)//Method Decl
{
length =a;
breadth =b;
}
int rectarea()
{
int area =length*breadth;
return area;
}
}
class sample
{
public static void main(String args[])
{
int area1;
area a1 = new area();
a1.getdata(12,15);
area1 = a1.rectarea();
System.out.println("area is "+area1);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
sample.java
C:Program
FilesJavajdk1.6.0_13bin>java sample
area is 180
Ex:28 get user input using scanner
import java.io.*;
import java.util.Scanner;
public class scanner
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
String i;
i=in.nextLine();
// String i= next();// Does not read spaces
//int i= nextInt();// read integer and for
float and double add them int the palce of
next"Int"
14. 14 | P a g e
System.out.println(i);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
scanner.java
C:Program
FilesJavajdk1.6.0_13bin>java scanner
10
10
Ex:29 Display of substring
class str1
{
public static void main(String args[])
{
String s1 ="hello";
String s2 ="hello";
System.out.println(s1.substring(0,2)+"lp");
char s3 = s1.charAt(3);
System.out.println(s3);
if (s1.equals(s2))
{
System.out.println("true");
}
else
{
System.out.println("false");
}
String s4 =s1.substring(0,2);
System.out.println(s4);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>java str1
help
l
true
he
Ex:30 call of an function
class functioncall
{
public static void funct1 ()
{
System.out.println ("Inside funct1");
}
public static int funct2 (int param)
{
System.out.println ("Inside funct2 with
param " + param);
return param * 2;
}
public static void main (String[] args)
{
int val;
System.out.println ("Inside main");
funct1();
System.out.println ("About to call funct2");
val = funct2(8);
System.out.println ("funct2 returned a
value of " + val);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
functioncall.java
C:Program
FilesJavajdk1.6.0_13bin>java
functioncall
Inside main
Inside funct1
About to call funct2
Inside funct2 with param 8
funct2 returned a value of 16
Ex:31 display the current date
15. 15 | P a g e
import java.util.*;
class hellodate
{
public static void main (String[] args)
{
System.out.println ("Hello, it's: ");
System.out.println(new Date());
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
hellodate.java
C:Program
FilesJavajdk1.6.0_13bin>java hellodate
Hello, it's:
Thu Sep 29 11:05:16 GMT+05:30 2011
Ex:32 Lab program (rational number)
import java.io.*;
import java.util.Scanner;
public class rational
{
public static void main(String args[])
{
System.out.println("The give required
Numbers ");
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
int i;
System.out.println("The given rational
Number is");
System.out.println(a+"/"+b);
if(a<b)
{
for(i=2;i<=9;i++)
{
while(a%i==0 && b%i==0)
{
a=a/i;
b=b/i;
}
}
}
else
{
for(i=2;i<=9;i++)
{
while(a%i==0 && b%i==0)
{
a=a/i;
b=b/i;
}
}
}
System.out.println("The simplified rational
number is");
System.out.println(a+"/"+b);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
rational.java
C:Program
FilesJavajdk1.6.0_13bin>java rational
The give required Numbers
3
54
The given rational Number is
3/54
The simplified rational number is
1/18
Ex:33 Reverse an number eg 10 01
public class ReverseNumber
{
public static void main(String[] args)
{
int number = 1234;
int reversedNumber = 0;
int temp = 0;
while(number > 0)
{
temp = number%10;
reversedNumber = reversedNumber * 10 +
temp;
16. 16 | P a g e
number = number/10;
}
System.out.println("Reversed Number is: "
+ reversedNumber);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
ReverseNumber.java
C:Program
FilesJavajdk1.6.0_13bin>java
ReverseNumber
Reversed Number is: 4321
Ex:34 Swap function call eg a=5 b=6 a=6
b=5
public class swap
{
public static void main(String[] args)
{
int num1 = 10;
int num2 = 20;
System.out.println("Before Swapping");
System.out.println("Value of num1 is :" +
num1);
System.out.println("Value of num2 is :"
+num2);
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("Before Swapping");
System.out.println("Value of num1 is :" +
num1);
System.out.println("Value of num2 is :"
+num2);
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
swap.java
C:Program
FilesJavajdk1.6.0_13bin>java swap
Before Swapping
Value of num1 is :10
Value of num2 is :20
Before Swapping
Value of num1 is :20
Value of num2 is :10
Ex:35 Program to compare string
import java.util.Scanner;
class Compare_Strings
{
public static void main(String args[])
{
String s1, s2;
Scanner in = new Scanner(System.in);
System.out.println("Enter the first string");
s1 = in.nextLine();
System.out.println("Enter the second
string");
s2 = in.nextLine();
if ( s1.compareTo(s2) > 0 )
System.out.println("First string is greater
than second.");
else if ( s1.compareTo(s2) < 0 )
System.out.println("First string is smaller
than second.");
else
System.out.println("Both strings are
equal.");
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>javac
Compare_Strings.java
17. 17 | P a g e
C:Program
FilesJavajdk1.6.0_13bin>java
Compare_Strings
Enter the first string
sun
Enter the second string
sun
Both strings are equal.
Ex:36 Sorting string in an array
import java.util.Arrays;
public class ArrayStringSorting {
public static void main(String[] args) {
String[] arrayList = new String[] {
"Thirumal", "Banana", "Apple", "Pears",
"Orange" };
System.out.println("Before sorting the
array: " + Arrays.asList(arrayList));
Arrays.sort(arrayList); // sort method used
to sort the array contents .
System.out.println("After sorting the
array: " + Arrays.asList(arrayList));
}
}
Output
C:Program
FilesJavajdk1.6.0_13bin>java
ArrayStringSorting
Before sorting the array: [Thirumal,
Banana, Apple, Pears, Orange]
After sorting the array: [Apple, Banana,
Orange, Pears, Thirumal]
Ex:37 Program to change the colour of
the background
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* @version 1.33 2007-06-12
* @author Cay Horstmann
*/
public class ActionTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
ActionFrame frame = new ActionFrame();
frame.setDefaultCloseOperation(JFrame.E
XIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
/**
* A frame with a panel that demonstrates
color change actions.
*/
class ActionFrame extends JFrame
{
public ActionFrame()
{
setTitle("ActionTest");
setSize(DEFAULT_WIDTH,
DEFAULT_HEIGHT);
buttonPanel = new JPanel();
// define actions
Action yellowAction = new
ColorAction("Yellow", new
ImageIcon("yellow-
ball.gif"),Color.YELLOW);
Action blueAction = new
ColorAction("Blue", new ImageIcon("blue-
ball.gif"), Color.BLUE);
Action redAction = new ColorAction("Red",
new ImageIcon("red-ball.gif"), Color.RED);
// add buttons for these actions
18. 18 | P a g e
buttonPanel.add(new
JButton(yellowAction));
buttonPanel.add(new
JButton(blueAction));
buttonPanel.add(new JButton(redAction));
// add panel to frame
add(buttonPanel);
// associate the Y, B, and R keys with
names
InputMap imap =
buttonPanel.getInputMap(JComponent.W
HEN_ANCESTOR_OF_FOCUSED_COMPONE
NT);
imap.put(KeyStroke.getKeyStroke("ctrl Y"),
"panel.yellow");
imap.put(KeyStroke.getKeyStroke("ctrl B"),
"panel.blue");
imap.put(KeyStroke.getKeyStroke("ctrl R"),
"panel.red");
// associate the names with actions
ActionMap amap =
buttonPanel.getActionMap();
amap.put("panel.yellow", yellowAction);
amap.put("panel.blue", blueAction);
amap.put("panel.red", redAction);
}
public class ColorAction extends
AbstractAction
{
/**
* Constructs a color action.
* @param name the name to show on the
button
* @param icon the icon to display on the
button
* @param c the background color
*/
public ColorAction(String name, Icon icon,
Color c)
{
putValue(Action.NAME, name);
putValue(Action.SMALL_ICON, icon);
putValue(Action.SHORT_DESCRIPTION,
"Set panel color to " +
name.toUpperCase());
putValue("color", c);
}
public void actionPerformed(ActionEvent
event)
{
Color c = (Color) getValue("color");
buttonPanel.setBackground(c);
}
}
private JPanel buttonPanel;
public static final int DEFAULT_WIDTH =
300;
public static final int DEFAULT_HEIGHT =
200;
}
Ex:38 Testing the button
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.E
XIT_ON_CLOSE);
frame.setVisible(true);
19. 19 | P a g e
}
});
}
}
@SuppressWarnings("serial")
class ButtonFrame extends JFrame
{
private final static int DEFAULT_WIDTH =
300;
private final static int DEFAULT_HEIGHT =
200;
private final JPanel buttonPanel;
public ButtonFrame()
{
this.setTitle("Button Frame");
this.setSize(DEFAULT_WIDTH,
DEFAULT_HEIGHT);
this.buttonPanel = new JPanel();
PanelButton yellowButton = new
PanelButton("Yellow", Color.YELLOW,
buttonPanel);
PanelButton redButton = new
PanelButton("Red", Color.RED,
buttonPanel);
PanelButton blueButton = new
PanelButton("Blue", Color.BLUE,
buttonPanel);
this.buttonPanel.add(yellowButton);
this.buttonPanel.add(redButton);
this.buttonPanel.add(blueButton);
// add panel to frame
this.add(this.buttonPanel);
}
}
@SuppressWarnings("serial")
class PanelButton extends JButton
implements ActionListener
{
private final Color buttonColor;
private final JPanel buttonPanel;
public PanelButton(String title, Color
buttonColor,
JPanel buttonPanel)
{
super(title);
this.buttonColor = buttonColor;
this.buttonPanel = buttonPanel;
this.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent
event)
{
buttonPanel.setBackground(this.buttonCol
or);
}
}
Ex:39 Mouse event
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.geom.*;
import javax.swing.*;
/**
* @version 1.32 2007-06-12
* @author Cay Horstmann
*/
public class MouseTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
MouseFrame frame = new MouseFrame();
frame.setDefaultCloseOperation(JFrame.E
XIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
20. 20 | P a g e
}
/**
* A frame containing a panel for testing
mouse operations
*/
class MouseFrame extends JFrame
{
public MouseFrame()
{
setTitle("MouseTest");
setSize(DEFAULT_WIDTH,
DEFAULT_HEIGHT);
// add component to frame
MouseComponent component = new
MouseComponent();
add(component);
}
public static final int DEFAULT_WIDTH =
300;
public static final int DEFAULT_HEIGHT =
200;
}
/**
* A component with mouse operations for
adding and removing squares.
*/
class MouseComponent extends
JComponent
{
public MouseComponent()
{
squares = new ArrayList<Rectangle2D>();
current = null;
addMouseListener(new MouseHandler());
addMouseMotionListener(new
MouseMotionHandler());
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
// draw all squares
for (Rectangle2D r : squares)
g2.draw(r);
}
/**
* Finds the first square containing a point.
* @param p a point
* @return the first square that contains p
*/
public Rectangle2D find(Point2D p)
{
for (Rectangle2D r : squares)
{
if (r.contains(p)) return r;
}
return null;
}
/**
* Adds a square to the collection.
* @param p the center of the square
*/
public void add(Point2D p)
{
double x = p.getX();
double y = p.getY();
current = new Rectangle2D.Double(x -
SIDELENGTH / 2, y - SIDELENGTH / 2,
SIDELENGTH,SIDELENGTH);
squares.add(current);
repaint();
}
/**
* Removes a square from the collection.
* @param s the square to remove
*/
public void remove(Rectangle2D s)
{
21. 21 | P a g e
if (s == null) return;
if (s == current) current = null;
squares.remove(s);
repaint();
}
private static final int SIDELENGTH = 10;
private ArrayList<Rectangle2D> squares;
private Rectangle2D current;
// the square containing the mouse cursor
private class MouseHandler extends
MouseAdapter
{
public void mousePressed(MouseEvent
event)
{
// add a new square if the cursor isn't
inside a square
current = find(event.getPoint());
if (current == null) add(event.getPoint());
}
public void mouseClicked(MouseEvent
event)
{
// remove the current square if double
clicked
current = find(event.getPoint());
if (current != null && event.getClickCount()
>= 2) remove(current);
}
}
private class MouseMotionHandler
implements MouseMotionListener
{
public void mouseMoved(MouseEvent
event)
{
// set the mouse cursor to cross hairs if it
is inside
// a rectangle
if (find(event.getPoint()) == null)
setCursor(Cursor.getDefaultCursor());
else
setCursor(Cursor.getPredefinedCursor(Cur
sor.HAND_CURSOR ));
}
public void mouseDragged(MouseEvent
event)
{
if (current != null)
{
int x = event.getX();
int y = event.getY();
// drag the current rectangle to center it at
(x, y)
current.setFrame(x - SIDELENGTH / 2, y -
SIDELENGTH / 2, SIDELENGTH,
SIDELENGTH);
repaint();
}
}
}
}
Implementation of look and feel
import java.awt.EventQueue;
import java.awt.event.*;
import javax.swing.*;
/**
* @version 1.32 2007-06-12
* @author Cay Horstmann
*/
public class PlafTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
22. 22 | P a g e
public void run()
{
PlafFrame frame = new PlafFrame();
frame.setDefaultCloseOperation(JFrame.E
XIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
/**
* A frame with a button panel for changing
look and feel
*/
class PlafFrame extends JFrame
{
public PlafFrame()
{
setTitle("PlafTest");
setSize(DEFAULT_WIDTH,
DEFAULT_HEIGHT);
buttonPanel = new JPanel();
UIManager.LookAndFeelInfo[] infos =
UIManager.getInstalledLookAndFeels();
for (UIManager.LookAndFeelInfo info :
infos)
makeButton(info.getName(),
info.getClassName());
add(buttonPanel);
}
/**
* Makes a button to change the pluggable
look and feel.
* @param name the button name
* @param plafName the name of the look
and feel class
*/
void makeButton(String name, final String
plafName)
{
// add button to panel
JButton button = new JButton(name);
buttonPanel.add(button);
// set button action
button.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent
event)
{
// button action: switch to the new look
and feel
try
{
UIManager.setLookAndFeel(plafName);
SwingUtilities.updateComponentTreeUI(Pl
afFrame.this);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
private JPanel buttonPanel;
public static final int DEFAULT_WIDTH =
300;
public static final int DEFAULT_HEIGHT =
200;
}