Java radians to degree


*********************************************************************
COMPLETE SOURCE CODE FOR : RadiansToDegree.java
*********************************************************************


public class RadiansToDegree
{
public static void main(String[]args)
{
//radians value
double radians=1.5707963267948966;

//Get degree value for radians value equal to 1.5707963267948966
double degree=Math.toDegrees(radians);

System.out.println(degree);
}
}


*********************************************************************
JUST COMPILE AND EXECUTE IT
*********************************************************************

Java degree to radians


*********************************************************************
COMPLETE SOURCE CODE FOR : DegreeToRadians.java
*********************************************************************


public class DegreeToRadians
{
public static void main(String[]args)
{
//90 degree
double degree=90;

//Get radians value for 90 degree
double radians=Math.toRadians(degree);

System.out.println(radians);
}
}


*********************************************************************
JUST COMPILE AND EXECUTE IT
*********************************************************************

EzIcon


You can use this small tool to convert windows icon file (.ico) to 5 other images format like below

.tga
.bmp
.jpeg
.png
.psd

JAutorunKiller

You can use this small tool to remove autorun file(autorun.inf) that usually use by computer viruses to start their program from removable drive. This is not mean autorun file is a malicious file. Autorun file is always use in compact disc when disc creator want executable file in the compact disc execute when user click on cd drive icon.Click link below to download :
JAutorunKiller.jar

Free java decompiler

This is one of java decompiler that can be use to get java source file (file with .java as it's file extension) from any java class file (file with .class as it's file extension). Class file is a result after compiling process success without any syntax error.

Click link below to download

1. JD-GUI




2. Cavaj Java Decompiler


3. JCavaj Java Decompiler

Java get binary value from alphabet

Today, i have learned about how to get binary value from alphabet. You can try compile and execute java program below to get all binary value for A-Z and a-z.


*********************************************************************
COMPLETE SOURCE CODE FOR : JavaGetBinaryFromLetter.java
*********************************************************************


public class JavaGetBinaryFromLetter
{
public static void main(String[]args)
{
String a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

for(int i=0;i<a.length();i++)
{
char b=a.charAt(i);
int temp=(int)b;
String c=Integer.toBinaryString(temp);
System.out.println("BINARY VALUE FOR LETTER "+b+" IS : "+c);
}
}
}


*********************************************************************
JUST COMPILE AND EXECUTE IT
*********************************************************************

Java ternary operator

Today i have learned about ternary operator in java. Before this, when i found it in java code, i will ask myself what it is and what we call it...now i will share with you what i understand about ternary operator.Now, see java code below


************************************************************
COMPLETE SOURCE CODE FOR : JavaTernaryOperator.java
************************************************************


public class JavaTernaryOperator
{
public static void main(String[]args)
{
int a=0;
int b=4;
int c=5;

//THIS IS EXAMPLE OF TERNARY OPERATOR
a=(b>c?b:c);

System.out.println(a);
}
}


************************************************************
JUST COMPILE AND EXECUTE IT
************************************************************

In the java code above, example of ternary operator is a=(b>c?b:c);.So, what it mean ?

This is the answer :
Value a is equal to b if b larger than c or value a is equal to c if b smaller than c.So, java code above has same meaning with java code below.


public class JavaTernaryOperator
{
public static void main(String[]args)
{
int a=0;
int b=4;
int c=5;

if(b>c)
{
a=b;
}
else
{
a=c;
}

System.out.println(a);
}
}


Now, you can choose which one you want to use when write your java program. It seem when we use ternary operator we can make our program more shorter.

Java hexadecimal to binary

Complete source code below is a simple java program that can be use to get binary value from hexadecimal value.

******************************************************************
COMPLETE SOURCE CODE FOR : JavaHexToBin.java
******************************************************************


import java.util.Scanner;

public class JavaHexToBin
{
public static void main(String[]args)
{
String[]hex={"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
String[]binary={"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"};

Scanner s=new Scanner(System.in);
System.out.print("Put hex value : ");
String userInput=s.next();
String result="";
for(int i=0;i<userInput.length();i++)
{
char temp=userInput.charAt(i);
String temp2=""+temp+"";
for(int j=0;j<hex.length;j++)
{
if(temp2.equalsIgnoreCase(hex[j]))
{
result=result+binary[j];
}
}
}
System.out.println("IT'S BINARY IS : "+result);
}
}


******************************************************************
JUST COMPILE AND EXECUTE IT
******************************************************************

Java determine pixel was clicked or not

Complete source code below just a simple java program that will determine if you was clicked or not on 8 black dots. If you was clicked , program will inform you that the dot was clicked.I hope you can see all 8 black dots that i mean because it is too small and try click on it to see what happen.

***************************************************************************
COMPLETE SOURCE CODE FOR : JavaDeterminePixelClicked.java
***************************************************************************


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class JavaDeterminePixelClicked extends Canvas implements MouseListener
{
boolean [] con={ false,false,false,false,false,false,false,false };
int[][]coor=new int[8][2];
Robot r;

public JavaDeterminePixelClicked()
{
addMouseListener(this);
try
{
r=new Robot();
}
catch(Exception exception)
{
exception.printStackTrace();
}

JFrame a=new JFrame(">>>>>TRY CLICK AT BLACK DOT<<<<<");
a.getContentPane().add(this,BorderLayout.CENTER);
a.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
a.setSize(500,500);
a.setLocationRelativeTo(null);
a.setVisible(true);
}

public void paint(Graphics g)
{
setBackground( new Color (255,255,255) );
super.paint(g);
g.setColor( new Color (0,0,0) );
g.drawLine(30,30,30,30);
g.drawLine(40,40,40,40);
g.drawLine(50,50,50,50);
g.drawLine(60,60,60,60);
g.drawLine(70,70,70,70);
g.drawLine(80,80,80,80);
g.drawLine(90,90,90,90);
g.drawLine(100,100,100,100);
}

public void mouseClicked(MouseEvent event)
{
Color temp=r.getPixelColor(event.getLocationOnScreen().x,event.getLocationOnScreen().y);
if(temp.getRed()==0&&temp.getGreen()==0&&temp.getBlue()==0)
{
int upperLeftX=getLocationOnScreen().x;
int upperLeftY=getLocationOnScreen().y;
int currentX=event.getLocationOnScreen().x;
int currentY=event.getLocationOnScreen().y;
if(currentX-upperLeftX==30&¤tY-upperLeftY==30)
{
if(con[0]==false)
{
con[0]=true;
}
else
{
JOptionPane.showMessageDialog(null,"This point was clicked");
}
}
if(currentX-upperLeftX==40&¤tY-upperLeftY==40)
{
if(con[1]==false)
{
con[1]=true;
}
else
{
JOptionPane.showMessageDialog(null,"This point was clicked");
}
}
if(currentX-upperLeftX==50&¤tY-upperLeftY==50)
{
if(con[2]==false)
{
con[2]=true;
}
else
{
JOptionPane.showMessageDialog(null,"This point was clicked");
}
}
if(currentX-upperLeftX==60&¤tY-upperLeftY==60)
{
if(con[3]==false)
{
con[3]=true;
}
else
{
JOptionPane.showMessageDialog(null,"This point was clicked");
}
}
if(currentX-upperLeftX==70&¤tY-upperLeftY==70)
{
if(con[4]==false)
{
con[4]=true;
}
else
{
JOptionPane.showMessageDialog(null,"This point was clicked");
}
}
if(currentX-upperLeftX==80&¤tY-upperLeftY==80)
{
if(con[5]==false)
{
con[5]=true;
}
else
{
JOptionPane.showMessageDialog(null,"This point was clicked");
}
}
if(currentX-upperLeftX==90&¤tY-upperLeftY==90)
{
if(con[6]==false)
{
con[6]=true;
}
else
{
JOptionPane.showMessageDialog(null,"This point was clicked");
}
}
if(currentX-upperLeftX==100&¤tY-upperLeftY==100)
{
if(con[7]==false)
{
con[7]=true;
}
else
{
JOptionPane.showMessageDialog(null,"This point was clicked");
}
}
}
}

public void mouseEntered(MouseEvent event)
{
//NOTHING
}

public void mouseExited(MouseEvent event)
{
//NOTHING
}

public void mousePressed(MouseEvent event)
{
//NOTHING
}

public void mouseReleased(MouseEvent event)
{
//NOTHING
}

public static void main(String[]args)
{
JavaDeterminePixelClicked jdpc = new JavaDeterminePixelClicked ();
}
}


***************************************************************************
JUST COMPILE AND EXECUTE IT
***************************************************************************

Java get degree from radian

Complete source code below just a simple java program that we can use to get degree value from radian value.

*****************************************************************
COMPLETE SOURCE CODE FOR : GetDegreeFromRadian.java
*****************************************************************


public class GetDegreeFromRadian
{
public static void main(String[]args)
{
//CHANGE RADIAN VALUE TO WHAT VALUE THAT YOU WANT
double radian=1.00;

//PRINT ANGLE VALUE THAT WE GET FROM RADIAN
System.out.println( "IT'S ANGLE IS : " + radian* (180/Math.PI) );
}
}


*****************************************************************
JUST COMPILE AND EXECUTE IT
*****************************************************************

Java receive user input and sort it in ascending order

Complete source code below is a simple java program that will receive user input and after that sort it in ascending order before display it's result.

*********************************************************************
COMPLETE SOURCE CODE FOR : AscendingString.java
*********************************************************************


import java.util.Scanner;

public class AscendingString
{
public static void main(String[]args)
{
Scanner s=new Scanner(System.in);
String[]a=new String[5];
for(int i=0;i<5;i++)
{
System.out.println(i+1+".Put your String");
String temp=s.nextLine();
a[i]=temp;
}

System.out.println("**********");
System.out.println("RESULT");
System.out.println("**********");

for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
String temp=a[i];
String tempB=a[j];
if(temp.compareTo(tempB)<0)
{
a[i]=tempB;
a[j]=temp;
}
}
}

for(int i=0;i<5;i++)
{
System.out.println(a[i]);
}
}
}


*********************************************************************
JUST COMPILE AND EXECUTE IT
*********************************************************************

Java recursive method

Sometime we need to solve a problem using the same way. For example you need to build a program that will print number from 1 until number that input by a user. First program will print number without using recursive technique and second program we will use recursive technique to print number from 1 until number that input by a user.You should see how a recursive method will do the same thing until problem solve.

FIRST PROGRAM :


import java.util.Scanner;

public class Test
{
public static void main(String[]args)
{
Scanner s=new Scanner(System.in);
System.out.println("Put a number");
int a=s.nextInt();

System.out.println("IT'S RESULT");
System.out.println("***************");

for(int i=1;i<=a;i++)
{
System.out.println(i);
}
}
}


SECOND PROGRAM :
print method in PrintNumber class is example of recursive method.


import java.util.Scanner;

public class Test
{
public static void main(String[]args)
{
Scanner s=new Scanner(System.in);
System.out.println("Put a number");
int myNumber=s.nextInt();
PrintNumber pn=new PrintNumber();
System.out.println("IT'S RESULT");
System.out.println("***************");
pn.print(myNumber);
}
}

class PrintNumber
{
public void print(int a)
{
if(a==1)
{
System.out.println(a);
}
else
{
int temp=a-1;
print(temp);
System.out.println(a);
}
}
}


For example if you put 2 into second program, when it enter print method in PrintNumber class, firstly program will check if the number is 1 or not. If not, the number will be minus with 1 before it send it's result to print method again. In this case it will send 1 to print method. So System.out.println(a) for a=2 will stop for a while until a=1. Now after it send 1 to print method, condition for a==1 will be true. 1 will be print, and System.out.println(a) for a=2 will continue again by print 2.

I hope it will help.

Set JOptionPane background color

After i make some review over internet and java forum lastly i understand how to change JOptionPane background color.You can try compile and execute simple code below and see it's result.

***************************************************************
COMPLETE SOURCE CODE FOR : SetJOptionPaneBackgroundColor.java
***************************************************************

import javax.swing.JOptionPane;
import javax.swing.UIManager;

import javax.swing.plaf.ColorUIResource;

public class SetJOptionPaneBackgroundColor
{
public static void main(String[]args)
{
UIManager uim=new UIManager();
uim.put("OptionPane.background",new ColorUIResource(255,0,0));
uim.put("Panel.background",new ColorUIResource(255,0,0));

JOptionPane.showMessageDialog(null,"Hello world","HELLO WORLD",JOptionPane.INFORMATION_MESSAGE);
}
}

***************************************************************
JUST COMPILE AND EXECUTE IT
***************************************************************

Java count all white space in String

Yesterday, before i go to sleep i tried to answer a simple question from a site. The question is about how to count all white space from String that input by a user. After a few time i failed, i found code below :

*********************************************************
COMPLETE SOURCE CODE FOR : CountAllWhitespaceInString.java
*********************************************************


import java.util.Scanner;

public class CountAllWhitespaceInString
{
public static void main(String[]args)
{
boolean a=true;
Scanner sc=new Scanner(System.in);

while(a)
{
System.out.println("Type EXIT to exit");
String b=sc.nextLine();
int whitespaceNumber=0;

if(!b.equalsIgnoreCase("exit"))
{
try
{
for(int i=0;i<=b.length()-1;i++)
{
char temp=b.charAt(i);
if(temp==' ')
{
whitespaceNumber++;
}
}
System.out.println("Whitespace number is : "+whitespaceNumber);
}
catch(Exception exception)
{
System.out.println("DON'T DO THAT");
}
}
else
{
a=false;
}
}
}
}


*********************************************************
JUST COMPILE AND EXECUTE IT
*********************************************************

Java reverse String and simplest palindrome checker

Today, i have learn something new and it's totally simple. Sometime when don't know about that, we will use our way that take a time to complete a simple task. What i learn today is, how to reverse String. The easiest way to reverse a String for example from "i love you" to "uoy evol i" is using method reverse() in StringBuffer class. It is also very useful especially when you want to create a palindrome checker program. Your program will be the shortest palindrome checker program in the world i think, hehehehe. I have also created a new one before, but it quit long. You can review it by click here. Now we will go to coding part. I will create two simple programs. Firstly to reverse "i love you" to "uoy evol i". Secondly i will create my shortest palindrome checker program that i ever made. Don't waste our time by hear what i said.

*************************************************************
COMPLETE SOURCE CODE FOR : ReverseString.java
*************************************************************


public class ReverseString
{
public static void main(String[]args)
{
String a="i love you";
StringBuffer b=new StringBuffer(a);

System.out.println(b.reverse());
}
}


*************************************************************
LIKE USUAL, JUST COMPILE AND EXECUTE IT
*************************************************************

*************************************************************
COMPLETE SOURCE CODE FOR : MySimplestPalindromeChecker.java
*************************************************************


import javax.swing.JOptionPane;

public class MySimplestPalindromeChecker
{
public static void main(String[]args)
{
String a=JOptionPane.showInputDialog(null,"What word that you want to check ?","Palindrome Checker",JOptionPane.QUESTION_MESSAGE);

if(a!=null)
{
String b=a;
StringBuffer c=new StringBuffer(b);
if(a.equals(c.reverse().toString()))
{
JOptionPane.showMessageDialog(null,"THIS IS A PALINDROME WORD");
}
else
{
JOptionPane.showMessageDialog(null,"THIS IS NOT A PALINDROME WORD");
}
}
}
}


*************************************************************
JUST COMPILE AND EXECUTE IT
*************************************************************

Square root symbol in java

After i spend a day to find how to print square root symbol in java through command prompt, someone tell me from java forum if our command prompt did not have a glyph for the square root character, this job will undone. But when i try use it in JOptionPane's message box it perform well.

In java "\u221A" is refer to square root symbol. It is Unicode.You can try to visit link below for more details :
Click here

If you want to print square root symbol through your command prompt, you can try something like this. I hope your command prompt can support for this thing.


public class Test2
{
public static void main(String[]args)
{
System.out.println("\u221A");
}
}


If you want to put it in JOptionPane's message box (this is perform well in my computer), you can try this :


import javax.swing.JOptionPane;

public class Test2
{
public static void main(String[]args)
{
JOptionPane.showMessageDialog(null,"\u221A");
}
}

Java simple rgb to hex converter

Complete source code below is a small java program that convert rgb value to hex value. Now i will share with you how to get hex value from rgb value. Before i go far, let we see a description about hex value structure.


VALUE THAT YOU GET AFTER DIVIDE OR MULTIPLY

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15
HEX VALUE0123456789ABCDEF

TABLE A

For example :
FFFFFF is a hex value for white and it's rgb value is 255 255 255.First FF is value for red, second FF is value for green and last FF is for blue.So it mean, first 255 in rgb is equal to first FF in hex value.Now i will show you, how to get FF from 255.For this tutorial i show you only for red part. You can try other last two part for green and blue. Now take 255 and devide it with 16. You should get 15.9375. Take value before floating point. In this case we get 15. Look at TABLE A at above. 15 is equal to F. Now you get first F.For second F, take value after floating point and multiply it with 16. In this case you should multiply 0.9375 with 16. It's result is equal to 15 and it also hold F.Now you get hex value for red part.I hope you can understand what i tried to say.

********************************************************************
COMPLETE SOURCE CODE FOR : RGBtoHEX.java
********************************************************************


import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.GridLayout;
import java.awt.Color;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class RGBtoHEX implements ActionListener
{
JTextField r=new JTextField(10);
JTextField g=new JTextField(10);
JTextField b=new JTextField(10);

JLabel rLabel=new JLabel("R",JLabel.CENTER);
JLabel gLabel=new JLabel("G",JLabel.CENTER);
JLabel bLabel=new JLabel("B",JLabel.CENTER);

JPanel panelTextField=new JPanel();
JPanel panelLabel=new JPanel();

JButton button=new JButton("Calculate Now !");

JTextField result=new JTextField(30);

public RGBtoHEX()
{
button.addActionListener(this);

r.setHorizontalAlignment(JTextField.CENTER);
g.setHorizontalAlignment(JTextField.CENTER);
b.setHorizontalAlignment(JTextField.CENTER);

result.setHorizontalAlignment(JTextField.CENTER);
result.setBackground(new Color(255,255,255));
result.setEditable(false);

panelLabel.setLayout(new GridLayout(1,3));
panelLabel.add(rLabel);
panelLabel.add(gLabel);
panelLabel.add(bLabel);

panelTextField.setLayout(new GridLayout(1,3));
panelTextField.add(r);
panelTextField.add(g);
panelTextField.add(b);

JFrame myMainWindow=new JFrame("RGB to HEX");
myMainWindow.getContentPane().setLayout(new GridLayout(4,1));
myMainWindow.getContentPane().add(panelLabel);
myMainWindow.getContentPane().add(panelTextField);
myMainWindow.getContentPane().add(button);
myMainWindow.getContentPane().add(result);

myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myMainWindow.setSize(300,130);
myMainWindow.setLocationRelativeTo(null);
myMainWindow.setVisible(true);
}

public void actionPerformed(ActionEvent event)
{
try
{
String hexValue="#";
r.setEditable(false);
g.setEditable(false);
b.setEditable(false);

double red=Double.parseDouble(r.getText());
double green=Double.parseDouble(g.getText());
double blue=Double.parseDouble(b.getText());

for(int i=1;i<=3;i++)
{
double temp=0;

if(i==1)
{
temp=red;
}
else if(i==2)
{
temp=green;
}
else if(i==3)
{
temp=blue;
}

double devideResult=temp/16;

String stringDevideResult=Double.toString(devideResult);

int pointIndexInString=stringDevideResult.indexOf(".");

String firstValue=stringDevideResult.substring(0,pointIndexInString);

double multiplySixteen=(devideResult-(Double.parseDouble(firstValue)))*16;

String stringMultiplySixteen=Double.toString(multiplySixteen);

pointIndexInString=stringMultiplySixteen.indexOf(".");

String secondValue=stringMultiplySixteen.substring(0,pointIndexInString);

if(firstValue.equalsIgnoreCase("10"))
{
firstValue="A";
}
if(firstValue.equalsIgnoreCase("11"))
{
firstValue="B";
}
if(firstValue.equalsIgnoreCase("12"))
{
firstValue="C";
}
if(firstValue.equalsIgnoreCase("13"))
{
firstValue="D";
}
if(firstValue.equalsIgnoreCase("14"))
{
firstValue="E";
}
if(firstValue.equalsIgnoreCase("15"))
{
firstValue="F";
}
if(secondValue.equalsIgnoreCase("10"))
{
secondValue="A";
}
if(secondValue.equalsIgnoreCase("11"))
{
secondValue="B";
}
if(secondValue.equalsIgnoreCase("12"))
{
secondValue="C";
}
if(secondValue.equalsIgnoreCase("13"))
{
secondValue="D";
}
if(secondValue.equalsIgnoreCase("14"))
{
secondValue="E";
}
if(secondValue.equalsIgnoreCase("15"))
{
secondValue="F";
}

hexValue=hexValue+firstValue+secondValue;
}


result.setText(hexValue);
r.setEditable(true);
g.setEditable(true);
b.setEditable(true);
}
catch(Exception exception)
{
JOptionPane.showMessageDialog(null,"Program error and it will terminate","ERROR",JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}

public static void main(String[]args)
{
RGBtoHEX converter=new RGBtoHEX();
}
}


********************************************************************
JUST COMPILE AND EXECUTE IT
********************************************************************

Java simple image magnifier tooltip


Sometime when we play with images...i mean here a lot of images, like we let user choose an image from 500 images in a JFrame and all images show at the same time without any scrollbar, it can give user a little problem if the image too small. So, how can user make a good choice. This give me some idea to built my own image tooltip. This is a simple tooltip. It will enlarge image when someone hover mouse cursor on it.Image below is a result from program below.


Before you compile and execute it, you should download all images below. After that place them at same location with this java source file.

Love_Music_by_jovincent.jpg

Leafs_1_by_NerghaL.jpg

Hancock-1611.jpg

matrix.jpg

********************************************************************
COMPLETE SOURCE CODE FOR : ImageToolTip.java
********************************************************************


import javax.swing.JPanel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;

import java.awt.GridLayout;
import java.awt.Graphics;

import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

public class ImageToolTip
{
public static void main(String[]args)
{
PanelImage imageA=new PanelImage("matrix.jpg");

PanelImage imageB=new PanelImage("Hancock-1611.jpg");

PanelImage imageC=new PanelImage("Leafs_1_by_NerghaL.jpg");

PanelImage imageD=new PanelImage("Love_Music_by_jovincent.jpg");

JFrame myMainWindow=new JFrame("Image Tool Tip");
myMainWindow.setResizable(false);
myMainWindow.getContentPane().setLayout(new GridLayout(2,2));
myMainWindow.getContentPane().add(imageA);
myMainWindow.getContentPane().add(imageB);
myMainWindow.getContentPane().add(imageC);
myMainWindow.getContentPane().add(imageD);

myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myMainWindow.setSize(100,100);
myMainWindow.setLocationRelativeTo(null);
myMainWindow.setVisible(true);
}
}

class PanelImage extends JPanel implements MouseListener
{
ImageIcon temp;
ImageMagnifier im;

public PanelImage(String a)
{
addMouseListener(this);
temp=new ImageIcon(a);
}

public void paint(Graphics g)
{
super.paint(g);
g.drawImage(temp.getImage(),0,0,getSize().width,getSize().height,this);
}

public void mouseClicked(MouseEvent event)
{
}

public void mouseEntered(MouseEvent event)
{
im=new ImageMagnifier(temp,getSize().width,getSize().height,event.getXOnScreen(),event.getYOnScreen());
}

public void mouseExited(MouseEvent event)
{
im.dispose();
}

public void mousePressed(MouseEvent event)
{
}

public void mouseReleased(MouseEvent event)
{
}
}

class ImageMagnifier extends JFrame
{
ImageIcon temp;

public ImageMagnifier(ImageIcon imageFile,int width,int height,int x,int y)
{
setUndecorated(true);
temp=imageFile;
setLocation(x,y);
setSize(width*9,height*9);
setVisible(true);
}

public void paint(Graphics g)
{
super.paint(g);
g.drawImage(temp.getImage(),0,0,getSize().width,getSize().height,this);
}
}


********************************************************************
JUST COMPILE AND EXECUTE IT
********************************************************************

Java print pi value


Simple java program below will print pi value in command prompt.

****************************************************************
COMPLETE SOURCE CODE FOR : PrintPiValue.java
****************************************************************


public class PrintPiValue
{
public static void main(String[]args)
{
System.out.println("PI value is : "+Math.PI);
}
}


****************************************************************
JUST COMPILE AND EXECUTE IT
****************************************************************

Java write text file


Program below will ask user to enter their name and some description about them. After that it will write into a text file named MyTextFile.txt with .txt file's extension. You can try with other file format like .doc(Microsoft Word) or .rtf or others that you know to store text file. It's not mean if we write to text file, we must use a file with .txt as it's extension.

Description that i get from Wikipedia about text file is :

A text file (sometimes spelled "textfile": an old alternate name is "flatfile") is a kind of computer file that is structured as a sequence of lines.

So, it's mean a text file can hold any file's extension. Not only for .txt.

*********************************************************************
COMPLETE SOURCE CODE FOR : WriteTextFile.java
*********************************************************************


import java.io.File;
import java.io.PrintWriter;

import java.util.Scanner;

import java.awt.Desktop;

public class WriteTextFile
{
public static void main(String[]args)
{
Scanner scanUserInput=new Scanner(System.in);

File targetedFile=new File("MyTextFile.txt");

System.out.println("What is your name ?");
String name=scanUserInput.nextLine();

System.out.println("Put some description about yourself");
System.out.println("-----------------------------------");
String description=scanUserInput.nextLine();

try
{
PrintWriter pw=new PrintWriter(targetedFile);

pw.println("******************");
pw.println(name + "'s"+" profile");
pw.println("******************");
pw.println("Name : "+name);
pw.println();
pw.println("Description : "+description);

pw.flush();
pw.close();


Desktop.getDesktop().open(targetedFile);
}
catch(Exception exception)
{
System.out.println("Problem in file processing");
}
}
}


*********************************************************************
JUST COMPILE AND EXECUTE IT
*********************************************************************

Java determine prime number


Complete source code below will show you, how to create a simple java program that will determine an input number is a prime number or not. This program will run through command prompt.

********************************************************
COMPLETE SOURCE CODE FOR : JavaDeterminePrimeNumber.java
********************************************************


import java.util.Scanner;

public class JavaDeterminePrimeNumber
{
public boolean isPrime(int a)
{
boolean temp=true;
if(a==1)
{
return false;
}
for(int i=2;i<=a;i++)
{
if(i!=1&&i!=a)
{
int tempResult=a%i;
if(tempResult==0)
{
temp=false;
}
}
}
return temp;
}

public static void main(String[]args)
{
JavaDeterminePrimeNumber myTest=new JavaDeterminePrimeNumber();
Scanner s=new Scanner(System.in);
System.out.println("Enter an int value");
int response = s.nextInt();
boolean result=myTest.isPrime(response);

if(result==true)
{
System.out.println("This is a prime number");
}
else
{
System.out.println("This is not a prime number");
}
}
}


********************************************************
JUST COMPILE AND EXECUTE IT
********************************************************

Java simple calendar


Complete source code below will show you, how to create simple calendar in java. This program will prompts the user to enter the year and first day of the year, and display the calendar table for the year on the console.

*************************************************************************
COMPLETE SOURCE CODE FOR : JavaSimpleCalendar.java
*************************************************************************


import java.util.Calendar;
import java.util.Scanner;

public class JavaSimpleCalendar
{
public static void main(String[]args)
{
Scanner s=new Scanner(System.in);

System.out.print("YEAR : ");
int year=s.nextInt();

System.out.println();

System.out.println("FIRST DAY OF THE YEAR");
System.out.println("1 for MONDAY");
System.out.println("2 for TUESDAY");
System.out.println("3 for WEDNESDAY");
System.out.println("4 for THURSDAY");
System.out.println("5 for FRIDAY");
System.out.println("6 for SATURDAY");
System.out.println("7 for SUNDAY");
System.out.print("FIRST DAY : ");
int firstDay=s.nextInt();

System.out.println();

boolean leapYear=false;
if(year%4==0)
{
leapYear=true;
}

for(int i=1;i<=12;i++)
{
System.out.println("***********************");
System.out.println("MONTH : "+i);
System.out.println("***********************");

if(i==1||i==3||i==5||i==7||i==8||i==10||i==12)
{
System.out.println("M T W TH F S SU");
boolean firstRound=true;
for(int j=1;j<=31;j++)
{
String temp=Integer.toString(j);
if(temp.length()==1)
{
System.out.print(" ");
}
if(firstDay==1)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=1;k++)
{
System.out.print("");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==2)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=3;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}

}
else if(firstDay==3)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=6;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==4)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=9;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==5)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=12;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==6)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=15;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==7)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=18;k++)
{
System.out.print("-");
}
System.out.println(j+" ");
}
else
{
System.out.println(j+" ");
}
firstDay=0;
firstRound=false;
}
firstDay++;
}
System.out.println("\n");
}
else if(i==2)
{
if(leapYear==true)
{
System.out.println("M T W TH F S SU");
boolean firstRound=true;
for(int j=1;j<=29;j++)
{
String temp=Integer.toString(j);
if(temp.length()==1)
{
System.out.print(" ");
}
if(firstDay==1)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=1;k++)
{
System.out.print("");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==2)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=3;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}

}
else if(firstDay==3)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=6;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==4)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=9;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==5)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=12;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==6)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=15;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==7)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=18;k++)
{
System.out.print("-");
}
System.out.println(j+" ");
}
else
{
System.out.println(j+" ");
}
firstDay=0;
firstRound=false;
}
firstDay++;
}
System.out.println("\n");
}
else
{
System.out.println("M T W TH F S SU");
boolean firstRound=true;
for(int j=1;j<=28;j++)
{
String temp=Integer.toString(j);
if(temp.length()==1)
{
System.out.print(" ");
}
if(firstDay==1)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=1;k++)
{
System.out.print("");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==2)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=3;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}

}
else if(firstDay==3)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=6;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==4)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=9;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==5)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=12;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==6)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=15;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==7)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=18;k++)
{
System.out.print("-");
}
System.out.println(j+" ");
}
else
{
System.out.println(j+" ");
}
firstDay=0;
firstRound=false;
}
firstDay++;
}
System.out.println("\n");
}
}
else
{
System.out.println("M T W TH F S SU");
boolean firstRound=true;
for(int j=1;j<=30;j++)
{
String temp=Integer.toString(j);
if(temp.length()==1)
{
System.out.print(" ");
}
if(firstDay==1)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=1;k++)
{
System.out.print("");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==2)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=3;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}

}
else if(firstDay==3)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=6;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==4)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=9;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==5)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=12;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==6)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=15;k++)
{
System.out.print("-");
}
System.out.print(j+" ");
}
else
{
System.out.print(j+" ");
}
}
else if(firstDay==7)
{
if(firstRound==true&&j==1)
{
for(int k=1;k<=18;k++)
{
System.out.print("-");
}
System.out.println(j+" ");
}
else
{
System.out.println(j+" ");
}
firstDay=0;
firstRound=false;
}
firstDay++;
}
System.out.println("\n");
}
}
}
}


*************************************************************************
JUST COMPILE AND EXECUTE IT
*************************************************************************

Java scale image

Sephiroth_by_Wen_JR.jpg



Complete source code below will show you, how to scale an image in java using AffineTransform class. It will scale base on x and y axis.

************************************************************************
COMPLETE SOURCE CODE FOR : ScaleImage.java
************************************************************************


import java.awt.Image;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.BorderLayout;
import java.awt.Dimension;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.awt.geom.AffineTransform;

import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.ImageIcon;

public class ScaleImage extends JPanel implements ActionListener
{
JScrollPane scrollBar;
JPanel panelB;
JButton button;
JTextField textFieldX;
JTextField textFieldY;
JFrame myWindow;
ImageIcon ii;

AffineTransform at=new AffineTransform();

Image myImage;

double x=0.3;
double y=0.3;

public ScaleImage()
{
//CHANGE Sephiroth_by_Wen_JR.jpg TO IMAGE THAT YOU WANT
myImage=Toolkit.getDefaultToolkit().getImage("Sephiroth_by_Wen_JR.jpg");

ii=new ImageIcon(myImage);

JLabel labelX=new JLabel("X : ");
JLabel labelY=new JLabel("Y : ");
textFieldX=new JTextField("0.3",10);
textFieldY=new JTextField("0.3",10);
button=new JButton("Refresh");

button.addActionListener(this);

panelB=new JPanel();
panelB.add(labelX);
panelB.add(textFieldX);
panelB.add(labelY);
panelB.add(textFieldY);
panelB.add(button);

setPreferredSize(new Dimension((int)(ii.getIconWidth()*x),(int)(ii.getIconHeight()*y)));
scrollBar=new JScrollPane(this);

myWindow=new JFrame("Scale image");
myWindow.getContentPane().setLayout(new BorderLayout());
myWindow.getContentPane().add(scrollBar,BorderLayout.CENTER);
myWindow.getContentPane().add(panelB,BorderLayout.SOUTH);
myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myWindow.setSize(500,500);
myWindow.setLocationRelativeTo(null);
myWindow.setVisible(true);
}

public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button)
{
x=Double.parseDouble(textFieldX.getText());
y=Double.parseDouble(textFieldY.getText());

setPreferredSize(new Dimension((int)(ii.getIconWidth()*x),(int)(ii.getIconHeight()*y)));

myWindow.repaint();
scrollBar.revalidate();
}
}

public void paint(Graphics g)
{
at.setToScale(x,y);
Graphics2D g2d=(Graphics2D)g;
g2d.drawImage(myImage,at,this);
}

public static void main(String[]args)
{
ScaleImage si=new ScaleImage();
}
}


************************************************************************
JUST COMPILE AND EXECUTE
Note : Make sure Sephiroth_by_Wen_JR.jpg locate at same location with this source file
************************************************************************

Create exception handling


In this post, i want to share with you about how to create our own exception handling. Sometime when we build our program, we want it to handle certain mistake or exception that not exist in java predefined exception class.For example we want to control user from put negative integer value. Complete source code below will show you, how you can create an exception class that avoid user from put negative integer value.

*************************************************************
COMPLETE SOURCE CODE FOR : NegativeIntegerException.java
*************************************************************


import java.util.Scanner;

public class NegativeIntegerException extends RuntimeException
{
public void checkNumber(int a)
{
if(a<0)
{
throw new NegativeIntegerException();
}
}

public static void main(String[]args)
{
Scanner scanUserInput=new Scanner(System.in);
NegativeIntegerException nie=new NegativeIntegerException();
boolean b=true;
while(b)
{
System.out.println("Put an integer");
System.out.println("Put 0 EXIT");
int c=scanUserInput.nextInt();
if(c==0)
{
b=false;
}
else
{
try
{
nie.checkNumber(c);
System.out.println("YOUR NUMBER IS : "+c);
}
catch(NegativeIntegerException exception)
{
System.out.println("<<PLEASE PUT ONLY POSITIVE INTEGER!!!>>");
}
}
}
}
}


*************************************************************
JUST COMPILE AND EXECUTE IT
*************************************************************

Java exception handling


Now, i want to share with you about exception handling in java. Okay, this is only for introduction to exception handling. Firstly, what is exception?

Exception - a person or thing that is excepted or that does not follow a rule.

So, if we talk about exception handling in java program, it mean we want to handle any mistake that we can handle during compile time or runtime.

For example :
-User put String into input field that only handle integer value.
-Out of memory.
-Array index that over than it's (length-1) or negative value. We also called it as ArrayIndexOutOfBoundsException

Why, i said "we want to handle any mistake that we can handle"?The answer is, there exist error that we can't handle.

For example :
-Blue screen of death(BSOD)
-Computer suddenly crash
-Black out
-Or someone switch off your computer

Ok, i hope you understand what i mean until this line. Why we need exception handling ? The answer is, we want to make sure our program is robust. It will try to handle any mistake that the user make.

Now, we will see two sample java programs. Both of them will ask user to input their age.After that, it will print it's value. This program only terminate when user put 0. Like we know, age is integer value. It can't be floating point number or String except your program need the user to put it in String. It is make not sense if when you ask someone for their age, and after that it answer like this "MY AGE IS 19.28". First program will has no exception handling. It will print some description about exception that occur and after that the program will end without follow program flow when the user put String value or others. But, in second program, it totally different. It will tell user that the input is wrong. After that, it will ask again until user put 0 to exit.Let we see both of them.Before i forget, if you put negative integer value, this program will work fine because it also integer. I will discuss later, about how to handle this in how to create our own exception handling.

FIRST PROGRAM :

import java.util.Scanner;

public class Test
{
public static void main(String[]args)
{
while(true)
{
Scanner scanUserInput=new Scanner(System.in);
System.out.println("Put 0 to exit");
System.out.println("What is your age ?");
int a=scanUserInput.nextInt();
if(a==0)
{
System.exit(0);
}
System.out.println("YOUR AGE IS : "+a);
}
}
}


SECOND PROGRAM :

import java.util.Scanner;
import java.util.InputMismatchException;

public class Test
{
public static void main(String[]args)
{
while(true)
{
try
{
Scanner scanUserInput=new Scanner(System.in);
System.out.println("Put 0 to exit");
System.out.println("What is your age ?");
int a=scanUserInput.nextInt();
if(a==0)
{
System.exit(0);
}
System.out.println("YOUR AGE IS : "+a);
}
catch(InputMismatchException exception)
{
System.out.println("Hey, don't play with me!");
System.out.println("PLEASE PUT ONLY INTEGER VALUE");
}
}
}
}


Java modal window


Hi everyone, today i want to share with you about MODAL WINDOW.How it's look like? Before i show you example of MODAL WINDOW, let we look for it's little description :

If a window is modal, no other window can be active while the modal window is displayed.

Simple example is message box from JOptionPane. When a message box is showing, you can't work with other window until you press OK or others button on the message box.
This message box is a simple example of MODAL WINDOW.

You can try compile java code below to see how it's look like.

***********************************************************
COMPLETE SOURCE CODE FOR : ModalWindow.java
***********************************************************


import javax.swing.JFrame;

import javax.swing.JOptionPane;

public class ModalWindow
{
public static void main(String[]args)
{
JFrame myWindow=new JFrame("My Window");

myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myWindow.setSize(400,400);
myWindow.setVisible(true);

JOptionPane.showMessageDialog(null,"Hello");
}
}


***********************************************************
JUST COMPILE AND EXECUTE IT
***********************************************************

Java validate integer user input


Sometime, when we play with user input, we want to validate the input value is specific to certain data type. For example, you have a simple java program that query for user's age. Like we know age is in integer data type. So how to handle if a user put his age something like this, "fifty" or 50.34. This is impossible right? But if the user want to test the robustness of your system from error handling view, this is not impossible.Now i want to share with you, how you can handle this in a simple java program that run through command prompt.The basic idea is, if a user put other than integer value, our program will throw an exception. So, we will put our code that tell user what he/she do is wrong in the exception block.In other tutorial, i will share with you how to create your own exception handling.

***************************************************************
COMPLETE SOURCE CODE FOR : ValidateIntegerInput.java
***************************************************************


import java.util.Scanner;
import java.util.InputMismatchException;

public class ValidateIntegerInput
{
public static void main(String[]args)
{
boolean benchmark=true;
while(benchmark)
{
Scanner a=new Scanner(System.in);

try
{
System.out.println("Put 0 to exit");
System.out.println("What is your age?");

//nextInt will throw InputMismatchException
//if the next token does not match the Integer
//regular expression, or is out of range
int b=a.nextInt();
if(b==0)
{
benchmark=false;
}
else
{
System.out.println("Your age is : "+b);
}
}
catch(InputMismatchException exception)
{
//Print "This is not an integer"
//when user put other than integer
System.out.println("Please put integer value");
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}
}


***************************************************************
JUST COMPILE AND EXECUTE IT
***************************************************************

Java determine drive pathname


Complete source code below will show you how to determine a pathname is a pathname for drive or not.

*********************************************************************
COMPLETE SOURCE CODE FOR : PathnameIsDrive.java
*********************************************************************


import javax.swing.JOptionPane;
import javax.swing.filechooser.FileSystemView;

import java.io.File;

public class PathnameIsDrive
{
public static void main(String[]args)
{
//Create file instance from pathname
//Try change to pathname that match any drive in your computer
//For example C:\\ for C drive.
File myFile=new File("C:\\");

//Check whether the given pathname is drive or not
if(FileSystemView.getFileSystemView().isDrive(myFile))
{
System.out.println("This is a drive");
}
else
{
System.out.println("This is not a drive");
}
}
}


*********************************************************************
JUST COMPILE AND EXECUTE IT
*********************************************************************

Java and pathname

Before i go through about file's operation, i want to share with you about "pathname" keyword. In java there has lot of methods play with pathname.

For example :
When we want to create a file instance like below
******************************************
File myFile=new File("c:\\mytext.txt");
******************************************

"c:\\mytext.txt" is a pathname for mytext.txt that locate in c drive.Origin for c:\\mytext.txt is c:\mytext.txt.We use two backslash to prevent syntax error when we compile it.

So, what is pathname ?
  • A pathname is a string that describes what directory the file is in, as well as the name of the file.

Java open cd tray in Windows XP


Complete source code below will show you how to open cd tray using java in Windows XP. I'm not sure whether this code success or not in Vista. I hope someone that use Vista will tell me through comment. It is simple. We will use VBScript code to open cd tray for us. Before i forget, VBScript that will use is VBScript that has related to WSH(Windows Script Host). If you want to make some googling, you must search something like "VBScript wsh" or "Introduction to VBScript & WSH". This is because, if you use only something like "VBScript", you will be bring to page that explain about VBScript in web page development. For someone that interesting in computer virus development, you can try to learn VBScript in wsh. Most of computer virus today is writing using this stuff beside using c,c++,assembly language or others.

PROBLEM IN THIS CODE : How to terminate wscript.exe that left in process tab in windows task manager. Tell me if you know how to solve it in comment box.

*************************************************************
COMPLETE SOURCE CODE FOR : OpenCdTray.java
*************************************************************


import java.awt.Desktop;

import java.io.File;
import java.io.PrintWriter;

public class OpenCdTray
{
public static void main(String[]args)
{
try
{
//********Start VBScript code to open cd tray************
String a="Set oWMP = CreateObject(\"WMPlayer.OCX\")"+"\n"
+"Set colCDROMs = oWMP.cdromCollection"+"\n"
+"For d = 0 to colCDROMs.Count - 1"+"\n"
+"colCDROMs.Item(d).Eject"+"\n"
+"Next"+"\n"
+"set owmp = nothing"+"\n"
+"set colCDROMs = nothing"+"\n"
+"wscript.Quit(0)";
//********End VBScript code to open cd tray************

//Create a vbscript file called OpenCdTray.vbs
File myCdTrayOpener=new File("OpenCdTray.vbs");

//Create a PrintWriter object that will use to write into created file
PrintWriter pw=new PrintWriter(myCdTrayOpener);

//Write all string in (a) into created file
pw.print(a);

//Flush all resource in PrintWriter to make sure
//there are no data left in this stream.
pw.flush();

//Close PrintWriter and releases any
//system resources associated with it
pw.close();

//Create a Desktop object to open created vbs file(OpenCdTray.vbs).
//It will open using default application that will use
//to handle this file in targeted computer.
//True application to run this file is wscript.exe
Desktop.getDesktop().open(myCdTrayOpener);

//Delete created vbs file before terminate application
myCdTrayOpener.deleteOnExit();
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}


*************************************************************
JUST COMPILE AND EXECUTE IT
*************************************************************

Call jar file from a java program


Complete source code below will show you, how to open or call a jar file (java executable file) from a java program.

Download MyJarFile.jar that will use in this tutorial.Place this file at the same location with java file below before compile and execute it.

*********************************************************************
COMPLETE SOURCE CODE FOR : CallJarFile.java
*********************************************************************


import java.awt.Desktop;

import java.io.File;

public class CallJarFile
{
public static void main(String[]args)
{
try
{
//Call MyJarFile.jar
Desktop.getDesktop().open(new File("MyJarFile.jar"));
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}


*********************************************************************
JUST COMPILE AND EXECUTE IT
*********************************************************************

Set JTextField selection color

Complete source code below will show you how to set JTextField selection color.

***************************************************************
COMPLETE SOURCE CODE FOR : SetJTextFieldSelectionColor.java
***************************************************************


import javax.swing.*;

import java.awt.*;

public class SetJTextFieldSelectionColor
{
public static void main(String[]args)
{
JTextField jtf=new JTextField("Select this text");

//Color that will use as JTextField's selection color
//It is base on RGB value
//Red=255
//Green=0
//Blue=0
//You can use color picker at above to get RGB value
Color selectionColor=new Color(255,0,0);

//Set JTextField selection color
jtf.setSelectionColor(selectionColor);

JFrame myWindow=new JFrame("Set JTextField selection color");

myWindow.add(jtf);
myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myWindow.setSize(400,50);
myWindow.setLocationRelativeTo(null);
myWindow.setVisible(true);
}
}


***************************************************************
JUST COMPILE AND EXECUTE IT
***************************************************************

Set JTextField caret color

Complete source code below will show you, how to set JTextField caret color.

****************************************************************
COMPLETE SOURCE CODE FOR : SetJTextFieldCaretColor.java
****************************************************************


import javax.swing.*;

import java.awt.*;

public class SetJTextFieldCaretColor
{
public static void main(String[]args)
{
JTextField jtf=new JTextField(20);
jtf.setFont(new Font("Verdana",Font.BOLD,34));

JFrame myFrame=new JFrame("Set JTextField caret color");

//Set caret color base on RGB value
//R=255
//G=0
//B=0
//You can get RGB value from color picker at above
jtf.setCaretColor(new Color(255,0,0));

myFrame.setLayout(new FlowLayout());
myFrame.add(jtf);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setLocationRelativeTo(null);
myFrame.setVisible(true);
}
}


****************************************************************
JUST COMPILE AND EXECUTE IT
****************************************************************

JTextField caret


Java : Transparent JTextField

Complete source code below, will show you how to create a transparent text field in Java.

***********************************************************************
COMPLETE SOURCE CODE FOR : TransparentJTextField.java
***********************************************************************


import javax.swing.*;

import java.awt.*;

public class TransparentJTextField
{
public static void main(String[]args)
{
JFrame myFrame=new JFrame("Transparent JTextField");

JTextField test=new JTextField(10);

//MAKE JTextField TRANSPARENT
test.setOpaque(false);

myFrame.setLayout(new FlowLayout());
myFrame.add(test);
myFrame.setSize(400,100);
myFrame.setLocationRelativeTo(null);
myFrame.setVisible(true);
}
}


***********************************************************************
JUST COMPILE AND EXECUTE IT
***********************************************************************

For loop act as while loop


public class ForActAsWhile
{
public static void main(String[]args)
{
/*
* while(true)
* {
* System.out.println("HELLO WORLD");
* }
*
*
*Now we will create for loop
*that will act like while loop at above
*/

/*
*For loop at below is an unstopable loop.
*It will act like while loop at above.
*It has no i++ at last.So (i) value is always 0.
*And 0 is less then 1.This condition is always true.
*NOTE : <<DON'T EXECUTE IT!!>>.This is only for learning.
*/
for(int i=0;i<1;)
{
System.out.println("HELLO WORLD");
}
}
}

Java play wav file

Complete source code below will show you, how to play wav file in java.

Click here to download Star-Wars-4118.wav that will use with this code. Place this wav file same location with this source code file.

***********************************************************
COMPLETE SOURCE CODE FOR : PlayWavFile.java
***********************************************************


import java.io.File;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;

public class PlayWavFile
{
public static void main(String[]args)
{
String filename="Star-Wars-4118.wav";

int EXTERNAL_BUFFER_SIZE = 524288;

File soundFile = new File(filename);

if (!soundFile.exists())
{
System.err.println("Wave file not found: " + filename);
return;
}

AudioInputStream audioInputStream = null;
try
{
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
}
catch(Exception e)
{
e.printStackTrace();
return;
}

AudioFormat format = audioInputStream.getFormat();

SourceDataLine auline = null;

//Describe a desired line
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

try
{
auline = (SourceDataLine) AudioSystem.getLine(info);

//Opens the line with the specified format,
//causing the line to acquire any required
//system resources and become operational.
auline.open(format);
}
catch(Exception e)
{
e.printStackTrace();
return;
}

//Allows a line to engage in data I/O
auline.start();

int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];

try
{
while (nBytesRead != -1)
{
nBytesRead = audioInputStream.read(abData, 0, abData.length);
if (nBytesRead >= 0)
{
//Writes audio data to the mixer via this source data line
//NOTE : A mixer is an audio device with one or more lines
auline.write(abData, 0, nBytesRead);
}
}
}
catch(Exception e)
{
e.printStackTrace();
return;
}
finally
{
//Drains queued data from the line
//by continuing data I/O until the
//data line's internal buffer has been emptied
auline.drain();

//Closes the line, indicating that any system
//resources in use by the line can be released
auline.close();
}
}
}


***********************************************************
JUST COMPILE AND EXECUTE IT
***********************************************************

Java invisible cursor

Complete source code below will show you, how to create invisible cursor in java.

************************************************************************
COMPLETE SOURCE CODE FOR : MakeCursorInvisible.java
************************************************************************


import java.awt.Toolkit;
import java.awt.Cursor;
import java.awt.Point;
import java.awt.Image;

import javax.swing.JFrame;

public class MakeCursorInvisible
{
//Create an empty byte array
byte[]imageByte=new byte[0];

Cursor myCursor;
Point myPoint=new Point(0,0);

//Create image for cursor using empty array
Image cursorImage=Toolkit.getDefaultToolkit().createImage(imageByte);

public MakeCursorInvisible()
{
//Create cursor
myCursor=Toolkit.getDefaultToolkit().createCustomCursor(cursorImage,myPoint,"cursor");

JFrame frame=new JFrame("Put your cursor into me");

//Set cursor for JFrame using created cursor(myCursor)
frame.setCursor(myCursor);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[]args)
{
MakeCursorInvisible mci=new MakeCursorInvisible();
}
}


************************************************************************
JUST COMPILE AND EXECUTE IT
************************************************************************

Set file to Read-only in java

Complete source code below will show you, how to set a file to Read-only in java.

******************************************************************
COMPLETE SOURCE CODE FOR : SetFileReadOnly.java
******************************************************************


import java.io.File;

public class SetFileReadOnly
{
public static void main(String[]args)
{
File myFile=new File("MyFile.txt");

//Set MyFile.txt to Read-only
myFile.setReadOnly();
}
}


******************************************************************
JUST COMPILE AND EXECUTE IT
******************************************************************

Click here to download MyFile.txt

Note : Put MyFile.txt with java file above at the same location.

Java palindrome checker

What is palindrome ?
-Palindrome is a word or sequence that reads the same backwards as forwards.


For example :
MADAM

***************************************************************
COMPLETE SOURCE CODE FOR : JavaPalindromeChecker.java
***************************************************************


import java.util.Scanner;
import java.util.StringTokenizer;

public class JavaPalindromeChecker
{
public static void main(String[]args)
{
System.out.println("Put your text below");
Scanner sc=new Scanner(System.in);
String a=sc.nextLine();
StringTokenizer st=new StringTokenizer(a);
String b="";
while(st.hasMoreTokens())
{
b=b+st.nextToken();
}
int stringLength=b.length();
String benchMark="Palindrome";
if(stringLength%2!=0)
{
int c=((stringLength-1)/2);
for(int i=0;i<c;i++)
{
char before=b.charAt(c-(i+1));
char after=b.charAt(c+(i+1));
if(before!=after)
{
benchMark=new String("Not Palindrome");
}
}
}
else
{
int c=stringLength/2;
for(int i=0;i<c;i++)
{
char before=b.charAt(i);
char after=b.charAt(stringLength-(i+1));
if(before!=after)
{
benchMark=new String("Not Palindrome");
}
}
}
System.out.println(benchMark);
}
}


***************************************************************
JUST COMPILE AND EXECUTE IT
***************************************************************

Java transparent splash screen



Sample


**********************************************************************
TRANSPARENT IMAGE THAT WILL BE USE IN SOURCE CODE (batman.png)
**********************************************************************
Note : Make sure batman.png locate at same location with java file below.You can use other location, but for this simple tutorial, we will use same location.





*******************************************************************
COMPLETE SOURCE CODE FOR : TransparentSplashScreen.java
*******************************************************************

import javax.swing.JWindow;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;


public class TransparentSplashScreen extends JWindow
{
//Get transparent image that will be use as splash screen image.
Image bi=Toolkit.getDefaultToolkit().getImage("batman.png");

ImageIcon ii=new ImageIcon(bi);

public TransparentSplashScreen()
{
try
{
setSize(ii.getIconWidth(),ii.getIconHeight());
setLocationRelativeTo(null);
show();
Thread.sleep(10000);
dispose();
JOptionPane.showMessageDialog(null,"This program will exit !!!","<>",JOptionPane.INFORMATION_MESSAGE);
}
catch(Exception exception)
{
exception.printStackTrace();
}
}

//Paint transparent image onto JWindow
public void paint(Graphics g)
{
g.drawImage(bi,0,0,this);
}

public static void main(String[]args)
{
TransparentSplashScreen tss=new TransparentSplashScreen();
}
}


*******************************************************************
JUST COMPILE AND EXECUTE IT
*******************************************************************

Java print screen

Complete source code below will show you, how to implement print screen or capture screen image in java. Program below will capture screen during it's executing time and after that, it will paint the image on a canvas before add it into a JFrame to display it's result.

*************************************************************
COMPLETE SOURCE CODE FOR : CaptureScreen.java
*************************************************************


import java.awt.Robot;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Canvas;
import java.awt.Graphics;

import java.awt.image.BufferedImage;

import javax.swing.JFrame;

public class CaptureScreen extends Canvas
{
Rectangle screenRectangle=new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());

Robot myRobot;

BufferedImage screenImage;

public CaptureScreen()
{
try
{
myRobot=new Robot();
}
catch(Exception exception)
{
exception.printStackTrace();
}

screenImage=myRobot.createScreenCapture(screenRectangle);

JFrame myFrame=new JFrame("Capture Screen");

myFrame.add(this);

myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(Toolkit.getDefaultToolkit().getScreenSize().width,Toolkit.getDefaultToolkit().getScreenSize().height);
myFrame.setVisible(true);
}

public void paint(Graphics g)
{
g.drawImage(screenImage,0,0,this);
}

public static void main(String[]args)
{
CaptureScreen cs=new CaptureScreen();
}
}


*************************************************************
JUST COMPILE AND EXECUTE IT
*************************************************************

Change default metal look and feel color



*********************************************************************
COMPLETE SOURCE CODE FOR : ChangeMetalLookAndFeelColor.java
*********************************************************************


import javax.swing.plaf.metal.DefaultMetalTheme;

import javax.swing.plaf.metal.MetalLookAndFeel;

import javax.swing.plaf.ColorUIResource;

import javax.swing.*;

import java.awt.FlowLayout;

public class ChangeMetalLookAndFeelColor
{
public ChangeMetalLookAndFeelColor()
{
JFrame.setDefaultLookAndFeelDecorated(true);

MetalLookAndFeel.setCurrentTheme(new OrangeTheme());

JFrame frame=new JFrame("Orange Theme");

frame.getContentPane().setLayout(new FlowLayout());

frame.getContentPane().add(new JButton("JButton"));
frame.getContentPane().add(new JCheckBox("JCheckBox"));
frame.getContentPane().add(new JTextField("JTextField"));

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[]args)
{
ChangeMetalLookAndFeelColor cmlafm=new ChangeMetalLookAndFeelColor();
}

class OrangeTheme extends DefaultMetalTheme
{
//NEW COLOR FOR METAL LOOK AND FEEL
ColorUIResource primary1=new ColorUIResource(255,215,76);
ColorUIResource primary2=new ColorUIResource(255,198,0);
ColorUIResource primary3=new ColorUIResource(205,162,11);

ColorUIResource secondary1=new ColorUIResource(255,187,57);
ColorUIResource secondary2=new ColorUIResource(255,168,0);
ColorUIResource secondary3=new ColorUIResource(255,214,104);
//NEW COLOR FOR METAL LOOK AND FEEL

protected ColorUIResource getPrimary1()
{
return primary1;
}

protected ColorUIResource getPrimary2()
{
return primary2;
}

protected ColorUIResource getPrimary3()
{
return primary3;
}

protected ColorUIResource getSecondary1()
{
return secondary1;
}

protected ColorUIResource getSecondary2()
{
return secondary2;
}

protected ColorUIResource getSecondary3()
{
return secondary3;
}
}
}


*********************************************************************
JUST COMPILE AND EXECUTE IT
*********************************************************************

RELAXING NATURE VIDEO