Search This Blog

Showing posts with label java code. Show all posts
Showing posts with label java code. Show all posts

Java Program to Hibernate Windows Operating System

Do you want to hibernate your Windows computer using java program? This is a java program to hibernate Windows operating System. If you execute this java program, it will hibernate your Windows computer instantly. The following is the java code to hibernate Windows:

try
 {
 Runtime.getRuntime().exec("shutdown /h");
 } catch (IOException ex) {}

How to Launch a Application or Executable Using Java Code with Command Line Arguments

In this post, we shall see how to launch an application with its command line arguments using Java code. Most applications take path of a file as command-line argument to open it. If we give path of an image file to mspaint application as command-line argument, the image will be opened in paint. The following java program launches mspaint with a command-line argument which is a path to an image.

 try
 {
 Runtime.getRuntime().exec("C:\\Windows\\System32\\mspaint.exe \"C:\\Users\\Shareef\\Desktop\\flower.jpg\"");
 } catch (IOException ex) {}

Arguments are separated by spaces. If a command-line argument contains space within it (such as a space in a path), it is recommended to enclose it within brackets.

Java Code to Restart Windows

Are you thinking how to restart Windows from Java. You can restart Windows operating system by executing a system command. You can restart windows by executing the system command shutdown /r /t 1. The following Java code will restart the windows computer when executed.

try {
    Runtime.getRuntime().exec("shutdown /r /t 1");
    } catch (IOException ex) {}

How to Schedule a Shutdown in Java - Java Code to Schedule a Shutdown

In this post, we will see how to schedule a shutdown in a computer using java program. For this, we execute the appropriate shutdown command after identifying the operating system. The following java code will schedule a shutdown after a 10 minute from execution of the code.

String os=System.getProperty("os.name").toLowerCase();
String command;
try
{
if(os.contains("windows"))
    {
    command="shutdown /s /t 600";
    }
else if(os.contains("linux")||os.contains("mac os x"))
    {
    command="shutdown -h +600";
    }
else
    throw new Exception("Unsupported OS");
Runtime.getRuntime().exec(command);
}catch(Exception ex){
JOptionPane.showMessageDialog(null,ex.getMessage());
}

Java Program for Animated Solution for Tower of Hanoi Puzzle Problem

This is a java program to solve towers of hanoi puzzle problem. This java program give solution for tower of hanoi problem with any number of disks. This program gives animated solution for tower of Hanoi problem. It demonstrates solving the tower of hanoi problem using animation in java.

The solution of hanoi problem given by this program is always optimal. You can enter the number of disks first. This lets you solve puzzle of any level of difficulty. The program is as follows.


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class HanoiAnimated extends JPanel{

static int tower[][];// the three towers' disks as stack
static int top[];//top of the three stacks
static int from,to;//moving 'from' tower number 'to' tower number
static int diskInAir;//number of disk moved (1 to n)
static int n,l,b,u;
static Color colors[]={Color.BLUE,Color.CYAN,Color.GREEN,Color.MAGENTA,Color.ORANGE,Color.PINK,Color.RED,Color.YELLOW};
public HanoiAnimated()
{
    tower=new int[3][10];
    top=new int[3];
}

static void push(int to, int diskno)
//putting disk on tower
{
tower[to-1][++top[to-1]]=diskno;
}

static int pop(int from)
//take topmost disk from tower
{
return(tower[from-1][top[from-1]--]);
}

Color getColor(int disknum)
{
return colors[disknum%8];
}

void drawStill(Graphics g)
{
int j,i,disk;
g.clearRect(0,0,getWidth(),getHeight());
for(j=1;j<=3;j++)
 {
 //draw tower
        g.setColor(Color.GRAY);
 g.fillRoundRect(j*l,u,5,b-u,1,1);
        
 //draw all disks on tower
 for(i=0;i<=top[j-1];i++)
  {
  disk=tower[j-1][i];
                g.setColor(getColor(disk));
  g.fillRect(j*l-15-disk*5,b-(i+1)*10,35+disk*10,10);
  }
 }
}

void drawFrame(Graphics g,int x,int y)
{
try{
drawStill(g);
g.setColor(getColor(diskInAir));
g.fillRect(x-15-diskInAir*5,y-10,35+diskInAir*10,10);
Thread.sleep(60);
}catch(InterruptedException ex){}
}

void animator(Graphics g)
//to show the movement of disk
{
int x,y,dif,sign;
diskInAir=pop(from);
x=from*l;
y=b-(top[from-1]+1)*10;
//taking disk upward from the tower
for(;y>u-20;y-=8)
 drawFrame(g, x, y);

y=u-20;
dif=to*l-x;
sign=dif/Math.abs(dif);
//moving disk towards a target tower
for(;Math.abs(x-to*l)>=24;x+=sign*12)
 drawFrame(g, x, y);
x=to*l;
//placing disk on a target tower
for(;y<b-(top[to-1]+1)*10;y+=8)
 drawFrame(g, x, y);
push(to,diskInAir);
drawStill(g);
}

void moveTopN(Graphics g, int n, int a, int b, int c) throws InterruptedException
//Move top n disk from tower 'a' to tower 'c'
//tower 'b' used for swapping
{
if(n>=1)
 {
 moveTopN(g,n-1,a,c,b);
 drawStill(g);
 Thread.sleep(700);
 from=a;
 to=c;
 //animating the move
 animator(g);
 moveTopN(g,n-1,b,a,c);
 }
}

public static void main(String[] args)
{

int i;
String s=JOptionPane.showInputDialog("Enter number of disks");
n=Integer.parseInt(s);
HanoiAnimated ha=new HanoiAnimated();
//setting all tower empty
for(i=0;i<3;i++)
 top[i]=-1;

//putting all disks on tower 'a'
for(i=n;i>0;i--)
 {
 push(1,i);
 }

JFrame fr=new JFrame();
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setLayout(new BorderLayout());
fr.setSize(640,360);
fr.add(ha);
ha.setSize(fr.getSize());
fr.setVisible(true);
l=ha.getWidth()/4;
b=ha.getHeight()-50;
u=b-n*12;
//start solving
try{
ha.moveTopN(ha.getGraphics(),n,1,2,3);
}catch(Exception ex){}
}

}


Java Program to Solve Tower of Hanoi Puzzle Problem

This is a java program to solve towers of hanoi puzzle problem. This simple java program gives solution for tower of hanoi problem with any number of disks. Tower of Hanoi is a mathematical game or puzzle. It is also called tower of brahma or Lucas' tower. There are three towers (or rods) and a number of disks of different diameters. Initially, The disks have hole at center so that it can slide on to the rods. Initially all disks are stacked on the first tower, say tower A, such that no disk is placed over a smaller disk. The goal or objective is to move all these disks from tower A (first tower) to tower C (third tower). But you should obey the following rules. The rules of towers of hanoi puzzle are:

Java Program to Find Sum of First N Terms of Geometric Progression

In this post we will see a java program to calculate sum of first n terms of a geometric progression. Geometric progression is also called GP (short for Geometric progression). The equation to find sum of first n terms of a geometric progression is as follows:

sum= a*(1-r^n)/(1-r)
sum of geometric progression, sum of gp, gp sum
sum of first n terms of geometric progression

Now, we will see a java program to find sum of first n terms of a GP. There is a case in which the above equation fails. When r (common ratio) is 1, the above equation won't work. Then every term in the GP will be same as first term. Therefore, in that case, the sum is a*n. The program is as follows:



import java.util.Scanner;

public class SumGP {
public static void main(String[] arg)
    {
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter first term, common ratio and n (number of terms)");
    int a=sc.nextInt(),r=sc.nextInt(),n=sc.nextInt();
        System.out.println((r==1)?"Sum is:"+a*n:"Sum is:"+(float)a*(1-Math.pow(r,n))/(1-r));
    }
}

Body Mass Index Calculator Using Java - Java Application Code

Body Mass Index Calculation is based on your weight and height. Body Mass Index (BMI) = weight/(height*height) where weight is in kilograms and height in meters. The following Java program takes weight and height as input and displays BMI and grades into underweight,Normal, Overweight or obesity.


import java.util.Scanner;

public class BMI {

public static void main(String[] arg)
    {
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter weight in kgs and height in meters");
    float bmi=sc.nextFloat()/(float)Math.pow(sc.nextFloat(),2);
    String s=(bmi<18.5)?"Underweight":(bmi<25)?"Normal weight":(bmi<30)?"Overweight":"Obesity";
    System.out.println("bmi: "+bmi+"   "+s);
    }
}

Calculate your BMI here

Weight (in kg):
Height (in meters):

Java Program To Send an XML File From Server to Client and Display it as Table

java program send xml file process cml file display as table java code xml parser
XML parsed and displayed as a table
In this post, i am writing a java program which will send an XML file over the network from Server to Client using Socket connection (TCP connection) and the client displays the received file as a table using swing. This program is based on my network lab experiment at college. The problem was:

Write a Program to read an xml file stored in the server. A client connected to the server gets the file and display the contents in a table using swing. The xml file contains details of books with the following fields.

Temperature Converter Program Using Java - Celsius, Kelvin, Fahrenheit, Reaumur and Rankine

free java temperature converter program. java temperature conversion using java program unit converter celsius kelvin fahrenheit and other different temperature scales
Java Temperature Converter Program
A responsive and accurate temperature converter program can be made using java. In this post, we
will see a good temperature converter code. This java temperature conversion application converts temperature between Celsius, Kelvin, Fahrenheit, Reaumur and Rankine scales. The java program for this temperature consists of methods for:
  • Celsius to Fahrenheit Conversion
  • Celsius to Kelvin Conversion
  • Celsius to Reaumur Conversion
  • Celsius to Rankine Conversion
  • Fahrenheit to Celsius Conversion
  • Fahrenheit to Kelvin Conversion
  • Fahrenheit to Reaumur Conversion
  • Fahrenheit to Rankine Conversion
  • Kelvin to Celsius Conversion
  • Kelvin to Fahrenheit Conversion
  • Kelvin to Reaumur Conversion
  • Kelvin to Rankine Conversion
  • Reaumur to Celsius conversion
  • Reaumur to Kelvin conversion
  • Reaumur to Fahrenheit conversion
  • Reaumur to Rankine conversion
  • Rankine to Celsius conversion
  • Rankine to Kelvin conversion
  • Rankine to Fahrenheit conversion
  • Rankine to Reaumur conversion

How to Filter Filetypes using File Extensions in JFileChooser - Java File Chooser

how to filter files in Jfilechooser by file types or file formats using extensions in filename java codefile name file type filefilter file filter filtering files
Screenshot of following example java program
In java, to browse files or folders from the file system, we use the JFileChooser class. You can use  the JFileChooser object in two modes, save mode or open mode. Here we discuss about filtering file type by file extensions for opening the file. By default, the JFileChooser object will have an AcceptAllFileFilter. This file filter will allow the user to select file of any file type. The file filter will display text All files. If you want to restrict the file chooser to open only one type of file, you should first remove the AcceptAllFileFilter. To do this, call the following method:

myfilechooser.removeChoosableFileFilter(createoropenchooser.getAcceptAllFileFilter());


How to Get Operating System Information in Java

Using java, you can gather some information about the operating system of the computer system on which the code is running. That us java provides some API classes that will help you to know about the operating system of the computer on which your application program is running. You can use System.getProperty() method for this purpose. There are some system property keys (strings) which can be used to get the respective information. The parameter to the System.getProperty() method is a string, the property key. The following values for the parameter string will give operating system related informations.

"os.arch"
Operating system architecture

"os.name"
Name of the operating system.

"os.version"
Version of Operating system.

Usage examples:

The following java program displays the Operating system related informations using getProperty() method.
System.out.println("Operating system architecture:"+System.getProperty("os.arch") ); System.out.println("Operating system Name:"+System.getProperty("os.name") ); System.out.println("Operating system version:"+System.getProperty("os.version") );

How to Make a Timer Controlled Progress Bar in Java

Java progress bar value updated using timer. update JProgressBar by thread, set progress of progress bar using timer thread
timer controlled progress bar in java
For some applications we require to use timer and progress-bars. Java has a swing class called
JProgressBar to create progress bars. It can have horizontal or vertical orientation. We can set the maximum and minimum values for JProgressBar. It can also have an indeterminate state in which the progressbar does not show a definite value and plays an animation to show that the process is in progress. JProgressBar can be used in indeterminate mode when neither can you determine how long a process would take to complete nor can you track its progress. In some other cases, you may have to use timers. Java provides a Timer class (Java.util.Timer). But you can create a very simple and flexible timer if you want. If the timer does not have crucial importance, you can use a thread that sleeps for every one second as a timer. I have been using such threads as timers for a long time and never failed. Such timers may fail (although very rarely) when the processor has very heavy workload.

Whatever, in a simple example, we will see how to create a timer using thread and how to use JProgressBar. In this example we control the JProgressBar using the timer. The progress in JProgressBar is set calling the method setValue(). In this example we are using a 1 minute timer. The progress bar should show the progress of timer. The java code for timer controlled JProgressBar is as follows:

Java Program to Send Image between Computers using UDP and Display it

java program java code java application to send image files (photos or pictures) between computer using UDP across Network
Java program to send image file over network using UDP
This was one of my experiments in Networking Lab. The aim was to write a java program to send a
picture (image) from a computer to another via network using UDP protocol and to display it at the receiving end. Simply, this is the java code to make a java application which can send images from one computer to another over a network. The program uses UDP (User Datagram Protocol). For both the computers (on either ends) the same code is enough. This app can act as a image sender or a receiver. The program uses a Progress bar (JProgressBar) to show the progress of the data transfer. Remember, transferring files over UDP is not easy because UDP does not guarantee ordered delivery, and not even successful delivery. So, here in this program, to ensure ordered delivery, the sender sends next chunk of data (DatagramPacket) only after receiving an acknowledgement for last sent packet. For acknowledgement, i used a string "ACK".

Chat Room Application using UDP in Java

UDP chatroom application in java source code Chatting using java UDP java chat application java group chat application
Java Chat room application using UDP
The following is a Java program for chatting. This chatting application uses UDP (User Datagram
Protocol) for chatting. The application gives you to options. One is to create a new chat room and the other is to join a chat room. The one who creates the chat room acts as a server for the chatroom. Others can join this chatroom id they know his IP address. This simple java chat room application is enough for server and clients. The GUI is basic one and not too attractive. Also i have used JOptionPane to reduce code. You may make improvements to the code. The chat rooms are not password protected. Anyone who know the server's IP address are granted access to the chat room. If you wish, you may improve the program. This Group chat application using java can be used in Local area networks. This code for java group chat program can be modified to enable chatting in multiple chat rooms. Try it.

How to download a file from internet Using java if URL is Given

Let us see how to download a file from internet in java. It is so simple. The following java program is a program which will download any file if the URL to the file to be downloaded is given. It also asks the user for destination to save the file. It displays the file size also. It also prints (displays) the progress of download. It uses the classes HttpURLConnection, URL, FileOutputStream, JFileChooser etc. The following java code is a simple java program to download a file from internet using URL. Here in this case, user has to give the file name and extension.


How to Get Path to Temp Directory for Current User in Java

In some cases, you may need to create temporary files. It is preferred to create temporary files and folders in the current user's temporary folder (temp directory) because, the user will be able to clean unwanted files. To get the path to the temp folder of current user, java provides a property key to be used with

System.getProperty()
. it is
"java.io.tmpdir"
.


The following code displays the path to the temporary folder for the current user.
System.out.println("temp directory ="+System.getProperty("java.io.tmpdir"));

How to Get Center Point of Screen in Java

If you want position your JFrame in center of screen, there is method for that. Read this post:

The LocalGraphicsEnvironment in Java will give you the center point of the display or screen. There is a static method getLocalGraphicsEnvironment() in GraphicsEnvironment class. To get the center point of the screen, you may use the following java code:


Point centre=GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();

You should include these import statements in the file.

import java.awt.Point; import java.awt.GraphicsEnvironment;

How to Set JFrame in Center of Screen

By default, a java application appears at top left corner of the screen. You might have seen that most of the applications appear in the middle of the screen. I will tell you how to center your java application on screen.

To set JFrame in center of Just call this.setLocationRelativeTo(null); in constructor of the JFrame. If you are using Netbeans IDE, it should be after calling initComponents() method. But if you call setLocation() method of JFrame after this, your JFrame will get relocated.

In most cases this works and this is enough. if you want to get the center point of the screen, just refer to the following post:

How to Get Center Point of Screen in Java

How to Set Background Color of a JFrame in Java

It is easy to set Background color of a JFrame in java. But still many people cannot do it (me too was once like this). Most such people may have tried this java code to set java JFrame background color: setBackground(Color.BLACK);. But this won't work. Instead, you should set the background color of the ContentPane of the JFrame. So, use the following code to set Background color of Frame in your Java Application.

getContentPane().setBackground(Color.BLACK);

or


getContentPane().setBackground(new Color(34,172,176));

Keep in mind that you have to import java.awt.Color; You can use the first one if you don't know RGB values of the desired color. Most common colors are defined as constants in Font class. If you know the RGB color values for your desired color, you can use the second example.