Rabu, 21 Desember 2011

Thread_Kelas RandomCounter

package Graphics;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;


public class RandomCounter implements Runnable {

    JTextField outputLabel;
    private int value;
    Thread thread;
    private boolean start = true;

    /** Creates a new instance of Counter */
    public RandomCounter() {
        setValue(0);
    }

    /** Creates a new instance of Counter */
    public RandomCounter(JTextField output) {
        outputLabel = output;
        setValue(0);
        thread = new Thread(this);
        thread.start();
    }

    public void run() {
        while(isStart()){
            outputLabel.setText("Counter: "+getValue());
            try {
               
                thread.sleep(200);
                setValue(getValue()+(int)(Math.random()*1000));
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

    public boolean isStart() {
        return start;
    }

    public void setStart(boolean start) {
        this.start = start;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;

    }
}


class SimpleGUI extends JFrame{
    private JButton clickButton,stopButton;
    private JTextField counterLabel;
    private RandomCounter counter;

    /** Creates a new instance of SimpleGUI */
    public SimpleGUI() {
        clickButton = new JButton("Start");
        stopButton = new JButton("Stop");

        counterLabel = new JTextField("Counter: ",20);

        this.setLayout(new FlowLayout());
        this.add(clickButton);
        this.add(stopButton);
        this.add(counterLabel);
       

        this.setTitle("Random Counter");
        this.setSize(300,200);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        clickButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                clickAction();
            }
        });

        stopButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                stopAction();
            }
        });
    }

    public void clickAction(){
        counter = new RandomCounter(counterLabel);
    }

    public void stopAction(){
        counter.setStart(false);
    }
}

class SimpleGUITester {

    /** Creates a new instance of SimpleGUITester */
    public SimpleGUITester() {
    }

    public static void main(String[] args) {
        SimpleGUI test = new SimpleGUI();
    }
}

Tidak ada komentar:

Posting Komentar