Search This Blog

Showing posts with label How to. Show all posts
Showing posts with label How to. Show all posts

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());
}

How to Shutdown Computer from Java - Java Code to Shutdown Computer

Java program can cause a computer to shutdown. In order to shutdown a computer using java code, you should execute the shutdown command in that operating system. The shutdown command is different in Windows and Linux. So, we first check for the operating system. Then we execute appropriate shutdown command.


try {
            String command;
            String os = System.getProperty("os.name").toLowerCase();
            if (os.contains("linux") || os.contains("mac os x"))
                command = "shutdown -h now";
            else if (os.contains("windows"))
                command = "shutdown /p";
            else
                throw new Exception("Unsupported operating system.");
            
            Runtime.getRuntime().exec(command);
            System.exit(0);

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }

For Linux and Mac OS X, the command for immediate shutdown is shutdown -h now. But in Windows, it is shutdown /p. The above java code checks the operating system. Then it assumes appropriate shutdown command and then executes it. This java code can shutdown a computer.

How to Logoff or Sign Out Windows Using Java Code

You can sign out the current user account from windows using java code. Sign out, log out or logoff button can be created using simple lines of code. To logout from Windows operating system using java code, use the following code:


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

As the above code shows, we are simply executing a cmd command shutdown /l. It is actually running shutdown.exe with parameter /l to force logoff. If you add above code in the actionPerformed() function of a button, the button becomes a logoff button. The following video will show an example in which a simple button is made into a logout button.



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 Reverse a String

Here, we will see a java program to reverse a string. The string is read and is displayed in reverse order. Java program to display an input string in reverse order.


import java.util.Scanner;

public class BMI {
public static void main(String[] arg)
    {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a string");
    String s=sc.nextLine();
    for(int i=s.length()-1;i>=0;i--)
            System.out.print(s.charAt(i));
    }
}

How to Load a Webpage in a Java App

Do you wonder how to load a webpage in your java application? It is simple. You can load a web document whether it is a web document in internet or a web document from a file in the localhost. I know three methods to do it. You can use JTextPane in java swing (javax.swing), JEditorPane in java swing (javax.swing) or WebView in javaFX (javafx.scene.web.WebView). We will discuss each method to display a webpage in a java application.

The three methods we are going to discuss are:
  • Using JTextPane
  • Using JEditorPane
  • Using WebView in JavaFX

What Does Modal and Modeless (Non Modal) Mean in Java

In java, the dialogue boxes in JOptionPane class are very popular. Now when we use dialogue boxes, whether it is message dialogue box, input dialogue or any other,  we may sometimes need to make the parent container (often JFrame or JWindow) not focusable. In another words, we may have to prevent a (parent) component taking input from the user while one of its member component is active. (You may have noticed that when error message boxes are displayed, you cannot click its parent window on many software until you dismiss it by clicking 'OK' or 'close'). Such a property of a member or child component, is called modality. In java, you can use JDialog with or without modality. A JDialog can be either modal or modeless.
A Modal dialog box is a dialog box that blocks input to some other top-level windows in the application. The modal dialog box captures the window focus until it is closed, usually in response to a button press.
A Modeless dialog box is a dialog box that does not block input to any other top level window while it is shown.
See following java code example:

How to Get User Related Informations in Java

In java, there are some methods that will help you to know some user related informations. Here also,

System.getProperty() 
method can give some informations about the user like:

User account name
User Working directory
User Home directory

To get the username of current user on the computer just call

System.getProperty("user.name")

It will return the current username as a string.


To get the working directory of current user on the computer call

System.getProperty("user.dir")

It will return the path of working directory of current user as a string.


To get the home directory (user's home folder) of current user on the computer call

System.getProperty("user.home")

It will return the path to home directory (folder) of current user as a string.

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 Get JRE installation Directory in a Java Application

To get the java runtime environment (JRE) installation directory of a computer, we can use the getProperty() method in System class. The key to be used for System.getProperty() method to get the java JRE installation directory is "java.home". System.getProperty("java.home") will return the java runtime environment(JRE) installation directory path as a string. the following code will display the jre installation directory path:


System.out.println(System.getProperty("java.home"));

How to Get Class Path in a Java Application


Class Path is the Path used to find directories and JAR archives containing class files. Elements of the class path are separated by platform-specific characters. To get class path from a running java application, you may use the getProperty() method in System class. The following java code will show you how to get class path in java.

String classpath=System.getProperty("java.class.path");
System.out.println("Class path="+ classpath);

How to Easily Copy a File to Another File or Location in Java

The Files class in java has many useful static methods to copy and move files, create temporary files or folders etc. To copy a file from one location to another in Java, there is a static method copy in Files class. The Files class is in java.nio.file package. The method Files.copy() takes three arguments (parameters) : Path of source file (as object of Path class), Path of destination file ( as object of Path class ) and an option parameter. The option parameter can be one of the following:

StandardCopyOption.REPLACE_EXISTING
If the target file exists, then the target file is replaced.

StandardCopyOption.COPY_ATTRIBUTES
Attempts to copy the file attributes associated with this file to the target file. The exact file attributes
that are copied is platform and file system dependent and therefore unspecified.

StandardCopyOption.NOFOLLOW_LINKS
Symbolic links are not followed. If the file is a symbolic link, then the symbolic link itself, not the target of the link, is copied.

You have to import java.nio.file.StandardCopyOption to use option parameters.

try{
File sourcefile=new File("audio.mp3");
File destination=new File(System.getProperty("java.io.tmpdir")+"\\temp.mp3");
Files.copy(sourcefile.toPath(),destination.toPath(),StandardCopyOption.COPY_ATTRIBUTES);
} catch (IOException ex) {
ex.printStackTrace();
}

For the copy method, there are two other overloaded method definitions. In one, instead of source file's path, inputstream is the first parameter and the rest are same. For the other overloaded definition, an outputstream object is the second parameter instead of destination path object and the rest are same.

Similarly, to move a file from one location to another, there is a method move() in Files class. The parameters of this method is also same as those of copy method.

How to Change Look and Feel of a Java Application

The following code fragment which can be used within main method or in constructor of the class tells you how to change the look and feel of a java program (java application). This sample code sets the LookAndFeel of the java application into Windows Look and Feel.


How to Remove Title bar from JFrame of Java Application

To remove the title bar completely, there is a method called setUndecorated() in java. It takes a boolean variable. If the boolean is true, the title bar will be removed. The following one is an example. The method setUndecorated() invoked with a true boolean argument, will remove the title bar from the JFrame MyJFrame. The method is called here from the constructor. You may call it anywhere from within the class scope.

How to Change Image in JButton in Java - Set Icon of JButton

In this post we are discussing how to change the image in button in Java. There may be situations in
change jbutton image java jbutton image jbutton background image jbutton image icon how to add image to jbutton in java swing jbutton picture adding image to jbutton add image to jbutton
Jbutton with Image set
programming where we want to know how to set JButton image in java or to change button icon in java. The java code to change the icon of a Jbutton is so short. We use the
setIcon()
method in JButton class. The setIcon method takes an ImageIcon object as an argument. I will show you a sample java code in which the icon of  button is set. First of all,  you have to copy the icon image (jpg, bmp, png or gif image) to the src folder in the project directory. You may also place it in some folder inside the src folder. If you are using netbeans IDE, you can simply drag and drop the image file into the desired folder in the projects pane. After copying the icon image to src folder (or any subfolder in it), use the following code to set it as the button's icon.
playbtn.setIcon(new ImageIcon(getClass().getResource("/manhaj/images/play.png")));