acak angka random

Wednesday, December 21, 2011


package ThreadAngkaRandom;
import javax.swing.*;
public class angkaRandom extends Thread{
    JTextField outTF;
    JButton startStop;
    int value;
    Thread thread;
    boolean start=false;
    public angkaRandom(){  }
    public angkaRandom(JTextField outTF, JButton startStop){
        this.outTF=outTF;
        this.startStop=startStop;
    }
    public void startRandom(){
        thread=new Thread(this);
        if(start==false){
            thread.start();
            start=true;
            startStop.setText("Stop");}
        else{
            start=false;
            startStop.setText("Start");  }
    }
    @Override
    public void run(){
        while(start) {
            value=(int) (Math.random()*1000);
            outTF.setText(String.valueOf(value));
            try{
                thread.sleep(300);}
            catch(InterruptedException ex){
                ex.printStackTrace();}
        }
    }
}




GUI:

package ThreadAngkaRandom;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class angkaRandomGUI extends JFrame {
    JTextField tf;
    JButton startStopBTN;
    JPanel panel;
    boolean start=true;
    angkaRandom counter;
    public angkaRandomGUI(){
        this.setLocation(200,200);
        this.setSize(300,200);
        this.setLayout(new BorderLayout());
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("Aplikasi Acak Angka");
        panel = new JPanel();
        panel.setLayout(new FlowLayout());
        startStopBTN = new JButton("start");
        tf = new JTextField(10);
        tf.setEditable(false);       
        panel.add(startStopBTN);
        panel.add(tf);
        this.setContentPane(panel);
        startStopBTN.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                angkaRandomAction();
            }
        });
    }
    public void angkaRandomAction(){
        if(start){
            counter=new angkaRandom(tf, startStopBTN);
            counter.startRandom();
            start=false;}
        else if(start==false) {
            counter.startRandom();
            start=true;}
    }
    public static void main(String[] args) {
        angkaRandomGUI test = new angkaRandomGUI();
        test.setVisible(true);
    }
}

Get This Comment Form

0 comment(s):

 
Copyright© 2010 | http://felisitasisme.com