Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.*;
- import javax.swing.*;
- import java.awt.event.*;
- public class Countdown extends JPanel implements Runnable{
- private Thread th;
- private JLabel p;
- private boolean partito=false;
- private boolean pausa;
- public Countdown(){
- setBackground(Color.white);
- setPreferredSize(new Dimension(500,200));
- JFrame f = new JFrame("Countdown");
- p = new JLabel("Contiamo....");
- add(p);
- f.setLayout(new BorderLayout());
- JPanel t = new JPanel();
- t.setPreferredSize(new Dimension (500,100));
- t.setBackground(Color.red);
- JButton bottonestart = new JButton("Start");
- ActionListener listenstart = new ActionListener(){
- public void actionPerformed(ActionEvent ae){
- if(!partito){
- start();
- System.out.println("è partito il countdown...");
- partito=true;
- }
- }
- };
- bottonestart.addActionListener(listenstart);
- t.add(bottonestart);
- JButton bottonepausa = new JButton("Pausa");
- ActionListener listenpausa = new ActionListener(){
- public void actionPerformed(ActionEvent ae){
- if(partito){
- stop();
- }
- partito=false;
- }
- };
- bottonepausa.addActionListener(listenpausa);
- t.add(bottonepausa);
- JButton bottonecolore = new JButton("Colore");
- ActionListener listencolore = new ActionListener(){
- public void actionPerformed(ActionEvent ae){
- //cambio colore del pannello
- Color colore = new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255));
- setBackground(colore);
- }
- };
- bottonecolore.addActionListener(listencolore);
- t.add(bottonecolore);
- f.add(this, BorderLayout.CENTER);
- f.add(t, BorderLayout.SOUTH);
- f.pack();
- f.setVisible(true);
- f.setResizable(false);
- f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- }
- public void stop(){
- System.out.println("Stai bloccando il thread"+th);
- th = null;
- }
- public boolean isRunning(){
- return th != null;
- }
- public void start(){
- if(!isRunning()){
- th = new Thread(this);
- System.out.println("Sta partendo il thread"+th);
- th.start();
- }
- }
- public void run(){
- while(isRunning()){ // se il thread Ë partito
- for(int i=10; i >= 0; i --){
- p.setText("siamo al numero .... "+i);
- try{
- Thread.sleep(1000);
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- }
- p.setText("Il countdown del thread "+th+" è finito :D");
- partito=false;
- stop();
- }
- }
- public static void main(String[] args) {
- new Countdown();
- }
- }
Add Comment
Please, Sign In to add comment