Pages

Jumat, 03 Februari 2012

mengakses perintah command prompt

setelah nyari-nyari info cara akses perintah 'cmd' windows, akhirnya ketemu juga. pada java, akses perintah cmd dapat dilakukan dengan memanfaatkan kelas Runtime dan Process, misal

Runtime runtime;
Process proc = runtime.exec("shutdown /s -t 00")

berikut salah satu contoh dari penerapannya untuk aplikasi sederhana mematikan komputer dengan menghitung mundur. aplikasi hasil otak atik, penambahan, pengurangan source code yg aku dapat dari net, udah lama jadi lupa referensinya darimana aja. terdiri dari 2 kelas utama dan satu kelas tidak utama :D. skenarionya ketika kelas pertama muncul kemudian dimasukkan nilai dan diklik ok, maka perintah shutdown dimulai dan dimunculkan dialog penghitung mundur. hasilnya sebagai berikut



kelas Shutdown.java, sebagai kelas input menit hitungan mundur
import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.io.*;

public class Shutdown extends JFrame implements ActionListener {

private JTextField menit;

private JLabel lbMenit;

private JButton btOK;

private JButton btCancel;

private JPanel pnButton;

private JPanel pnText;

private JPanel pnUtama;

private Runtime runtime;

private Process proc;

private Countdown count;

public Shutdown() {

super();

addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent evt) {

                System.exit(0);

            }

        });

this.setIconImage(java.awt.Toolkit.getDefaultToolkit().getImage("shutup.png"));

this.setTitle("shutdown PC");

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

int w = this.getSize().width;

int h = this.getSize().height;

int x = (dim.width-w)/2;

int y = (dim.height-h)/2;

this.setSize(100,100);

this.setLocation(x,y);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

menit = new JTextField(3);

JLabel lbWarning = new JLabel();

lbWarning.setText("proses shutdown tidak dapat dihentikan");

lbWarning.setHorizontalAlignment(JLabel.CENTER);

lbWarning.setVerticalAlignment(JLabel.CENTER);

lbMenit = new JLabel("menit :");

lbMenit.setHorizontalAlignment(JLabel.CENTER);

lbMenit.setVerticalAlignment(JLabel.CENTER);

btOK = new JButton("OK");

btCancel = new JButton("Batal");

pnButton = new JPanel();

pnText = new JPanel();

pnUtama = new JPanel();

pnButton.setLayout(new FlowLayout());

pnText.setLayout(new BorderLayout());

pnUtama.setLayout(new GridLayout(3,1));

//this.add(pnUtama, new BorderLayout());

pnButton.add(btOK);

pnButton.add(btCancel);

pnText.add(menit, BorderLayout.CENTER);

pnText.add(lbMenit, BorderLayout.WEST);

pnUtama.add(lbWarning);

pnUtama.add(pnText);

pnUtama.add(pnButton);

this.add(pnUtama);

runtime = Runtime.getRuntime();

//Process proc;

btOK.addActionListener(this);

btCancel.addActionListener(this);

this.pack();

}

//method untuk melakukan pengujian input angka

public boolean containsOnlyNumbers(String str) {

        

        //It can't contain only numbers if it's null or empty...

        if (str == null || str.length() == 0)

            return false;

        

        for (int i = 0; i < str.length(); i++) {

            //If we find a non-digit character we return false.

            if (!Character.isDigit(str.charAt(i)))

                return false;

        }

        

        return true;

    }

public void actionPerformed(ActionEvent e) {

if(e.getSource() == this.btOK) {

String menits = menit.getText();

try{

if(containsOnlyNumbers(menits)) {

int menitss = Integer.parseInt(menits);

int detik = menitss * 60;

proc = runtime.exec("shutdown /s -t "+ detik);

//proc = runtime.exec("echo biasa ae");

count = new Countdown(menitss);

count.setVisible(true);

//count.start();

this.setVisible(false);

}else{

JOptionPane.showMessageDialog(null, "yang anda masukkan bukan angka, masukkan angka dalam menit!");

}

}catch(IOException ex){

//JOptionPane.showMessageDialog(null, "yang anda masukkan bukan angka, masukkan angka dalam menit!");

ex.printStackTrace();

}

}else if(e.getSource() == this.btCancel){

System.exit(0);

}

}

public static void main(String []args) {

try {

UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

Shutdown shutdown = new Shutdown();

shutdown.setVisible(true);

} catch (Exception e) { }

//new SwingApplication();

}
::kelas Countdown.java
import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class Countdown extends JDialog implements ActionListener{

private JLabel lbCountdown;

private JButton btnCancel;

private JPanel pnCountdown;

private int detik = 0;

private int menit = 0;

private int jam = 0;

private Timer timer;

public Countdown(int menits){

super();

this.setTitle("countdown");

try {

UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

} catch (Exception ex) { }

this.menit = (menits%60)-1;

detik = 60;

this.jam = menits/60;

this.setIconImage(java.awt.Toolkit.getDefaultToolkit().getImage("timer.png"));

lbCountdown = new JLabel();

lbCountdown.setFont(new Font("Arial", Font.BOLD, 24));

lbCountdown.setHorizontalAlignment(JLabel.CENTER);

lbCountdown.setVerticalAlignment(JLabel.CENTER);

btnCancel = new JButton("tutup");

pnCountdown = new JPanel();

lbCountdown.setText("0" + jam + " : 0" + menit + " : 0" + detik);

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

int x = this.getSize().width;

int y = this.getSize().height;

this.setLocation((dim.width-x)/2,(dim.height-y)/2);

pnCountdown.setLayout(new GridLayout(2,1));

pnCountdown.add(lbCountdown);

pnCountdown.add(btnCancel);

this.add(pnCountdown);

btnCancel.addActionListener(this);

this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

this.pack();

hitCountdown();

start();

}

private void hitCountdown() {

if(timer==null){

timer = new Timer(1000, new ActionListener() {

public void actionPerformed(ActionEvent e) {

if(menit == 0 && (detik == 0 && jam > 0)){

detik = 59;

menit = 59;

jam--;

}else if(detik == 0 && (menit > 0 || jam > 0)) {

detik = 59;

menit--;

}else if(detik > 0 && (menit > 0 || jam > 0)){

detik--;

}else if(detik > 0 && (menit == 0 || jam == 0)){

lbCountdown.setForeground(Color.RED);

detik--;

}else if(menit == 0 && jam > 0){

menit = 59;

jam--;

}else if(menit>0 && jam > 0) {

menit--;

}else if(detik == 0 && menit == 0 && jam == 0){

stop();

detik = menit = jam = 0;

System.exit(0);

}

TimeScan ts = new TimeScan(detik, menit, jam);

lbCountdown.setText(ts.getHours() + " : " + ts.getMinutes() + " : " + ts.getSeconds());

}

});

}

}

public void stop(){

timer.stop();

}

public void start(){

timer.start();

}

public void actionPerformed(ActionEvent e) {

if(e.getSource()==btnCancel) {

System.exit(0);

}

}

}

::kelas Timescan.java digunakan untuk pengaturan tampilan jam menit dan detik saja
public class TimeScan

{

  private String timeSecond;

  private String timeMinutes;

  private String timeHours;

  public TimeScan()

  {

  }

  public TimeScan(int detik, int menit, int jam)

  {

    String nullD = ""; String nullM = ""; String nullJ = "";

    if ((detik < 10) && (detik >= 0)) {

      nullD = "0";

    }

    if ((menit < 10) && (menit >= 0)) {

      nullM = "0";

    }

    if (jam < 10) {

      nullJ = "0";

    }

    this.timeSecond = (nullD + detik + "");

    this.timeMinutes = (nullM + menit + "");

    this.timeHours = (nullJ + jam + "");

  }

  public String getSeconds()

  {

    return this.timeSecond;

  }

  public String getHours() {

    return this.timeHours;

  }

  public String getMinutes() {

    return this.timeMinutes;

  }

}


semoga bermanfaat!

test

1 komentar:

  1. thanks infonya kk. akhirnya sy dpt juga.
    saran aja ni, tambahin link download source codex juga biar blebih mudah dpelajari.

    BalasHapus