Rabu, 21 Desember 2011

Thread_Kelas Counter

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;


public class Counter implements Runnable{
    JLabel outputLabel;
    private int value;
    Thread thread;
    private boolean start = true;

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

    /** Creates a new instance of Counter */
    public Counter(JLabel 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() + 1);
            } 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 JLabel counterLabel;
    private Counter counter;

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

        counterLabel = new JLabel("Counter: ");

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

        this.setTitle("Thread application");
        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 Counter(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