try { Runtime.getRuntime().exec("shutdown /r /t 1"); } catch (IOException ex) {}
Tutorials, tips and tricks about java programming language. Answers for many doubts about java programming language. Answering many howtos. Sample java projects and source code, java games, java programs for java practical labs.
Search This Blog
Java Code to Restart Windows
How to Schedule a Shutdown in Java - Java Code to Schedule a Shutdown
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
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
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
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
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
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
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.How to Get JRE installation Directory in a Java Application
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.
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.
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
How to Remove Title bar from JFrame of Java Application
How to Change Image in JButton in Java - Set Icon of JButton
Jbutton with Image set |
playbtn.setIcon(new ImageIcon(getClass().getResource("/manhaj/images/play.png"))); |