Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Timer that could work when is closed doesn't work correctly

  1. #1
    Junior Member
    Join Date
    Sep 2022
    Posts
    9
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Timer that could work when is closed doesn't work correctly

    Hello, I made a timer that shows an image when the time runs out, but I wanna make it work when I close the program and when I open it again, the time still running, for that I save the current miliseconds when the timer was started and the remaining time and if the time is running in a JSON file when I close the window and thus stopping the program, and read that data when I re-run the program
    But when I close the window when the timer is running the program is still running and I have to force the stop, the JSON file is still written, but when I re-run the program, the timer appears as finished when it shouldn't, what's wrong?
    import org.json.JSONObject;
    import org.json.JSONTokener;
     
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.nio.file.Files;
    import java.nio.file.Paths;
     
    public class Temporizador extends JFrame {
        private static final int DELAY = 10; // Milésimas de segundo
        private static final long TIEMPO = 86400000/DELAY; // En centésimas de segundo
        // Edit these if you wanna test it
        private static final String ROUTE = "C:\\Users\\SEBAS\\Documents\\NetBeansProjects\\OtroTemporizador";
        private static final String IMAGEN = ROUTE + "\\Imagenes\\Imagen.jpg";
        private static final String DATA = ROUTE + "\\Data\\Data.json";
     
        private final JButton iniciar;
        private final JLabel imagen;
     
        private Timer reloj;
        private long tiempoRestante;
        private Data data;
     
        public static void main(String[] args) {
            new Temporizador();
        }
     
        private Temporizador() {
            data = readFile();
     
            setTitle("Temporizador");
            setSize(800, 600);
            setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
            setResizable(false);
            setLocationRelativeTo(null);
     
            JPanel panel = new JPanel();
            panel.setLayout(null);
     
            imagen = new JLabel();
            imagen.setLocation(0, 90);
            imagen.setSize(600, 510);
            imagen.setPreferredSize(new Dimension(600, 510));
            imagen.setOpaque(true);
            imagen.setBackground(Color.WHITE);
            imagen.setFont(new Font("Courier", Font.BOLD,75));
     
            iniciar = new JButton();
            iniciar.setText("Correr");
            iniciar.setLocation(0, 0);
            iniciar.setSize(100, 30);
            iniciar.setPreferredSize(new Dimension(100, 30));
            iniciar.setVisible(true);
            iniciar.addActionListener((event) -> {
                startTimer(TIEMPO);
            });
     
            panel.add(imagen);
            add(iniciar);
            add(panel);
     
            // Guardar y/o checkear que se halla guardado información
     
            if (data.running) {
                startTimer((data.remaining - (System.currentTimeMillis() - data.start)) / DELAY);
            }
     
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    if (data.running) {
                        data.remaining = tiempoRestante * DELAY;
                        writeFile(data);
                    }
                    else {
                        writeFile(new Data());
                    }
                    e.getWindow().dispose();
                }
            });
     
            setVisible(true);
        }
     
        private void startTimer(long time) {
            tiempoRestante = time;
            data.running = true;
            data.start = System.currentTimeMillis();
            reloj = new Timer(DELAY, (e) -> {
                updateTiempo();
                if (tiempoRestante <= 0) {
                    reloj.stop();
                    data.running = false;
                    showImage();
                }
            });
            reloj.start();
        }
     
        private void showImage() {
            File file = new File(IMAGEN);
            try {
                BufferedImage bufferedImage = ImageIO.read(file);
                imagen.setIcon(new ImageIcon(bufferedImage));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
     
        private static final int secDiv = 1000/DELAY;
        private static final int minDiv = 60 * secDiv;
        private static final int hourDiv = 60 * minDiv;
     
        private void updateTiempo() {
            tiempoRestante--;
            long cent = tiempoRestante % secDiv;
            long sec = (tiempoRestante / secDiv) % 60;
            long min = (tiempoRestante / minDiv) % 60;
            long hours = (tiempoRestante/ hourDiv);
     
            imagen.setText((hours < 10 ? "0" : "") + hours + ":" + (min < 10 ? "0" : "") + min + ":" + (sec < 10 ? "0" : "") + sec + ":" + (cent < 10 ? "0" : "") + cent);
        }
     
        private static class Data {
            long start = 0; // Milisegundos
            long remaining = 0; // Milisegundos
            boolean running = false;
        }
     
        private static Data readFile() {
            File file = new File(DATA);
            Data data = new Data();
     
            if (!file.exists() || file.length() == 0)
                return data;
     
            try {
                JSONTokener parser = new JSONTokener(new FileInputStream(file));
                JSONObject obj = new JSONObject(parser);
     
                data.start = obj.getInt("start");
                data.remaining = obj.getInt("remaining");
                data.running = obj.getBoolean("running");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
     
            return data;
        }
     
        private static void writeFile(Data data) {
            JSONObject obj = new JSONObject();
            obj.put("start", data.start);
            obj.put("remaining", data.remaining);
            obj.put("running", data.running);
     
            try {
                File file = new File(DATA);
                BufferedWriter writer = Files.newBufferedWriter(Paths.get(file.toURI()));
                obj.write(writer);
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Timer that could work when is closed doesn't work correctly

    when I close the window when the timer is running
    Should the window closing code stop the timer?

    How can the program be execute for testing? It needs a json file.
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    HerlySQR (September 27th, 2022)

  4. #3
    Junior Member
    Join Date
    Sep 2022
    Posts
    9
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Timer that could work when is closed doesn't work correctly

    Quote Originally Posted by Norm View Post
    Should the window closing code stop the timer?

    How can the program be execute for testing? It needs a json file.
    I don't know if it should, do I try it?
    And the json file is automatically created if don't exists, you just need to edit the file routes in the top of the code to test it correctly.

    Edit: stopping the timer solved the problem of the program not stopping when I close the window, thanks, but why when I re-run the program, the timer is ended when it shouldn't? Does it have to do with this?
    if (data.running) {
        startTimer((data.remaining - (System.currentTimeMillis() - data.start)) / DELAY);
    }

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Timer that could work when is closed doesn't work correctly

    when I re-run the program, the timer is ended when it shouldn't
    What values cause the timer to end? Print them out so you can see them.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #5
    Junior Member
    Join Date
    Sep 2022
    Posts
    9
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Timer that could work when is closed doesn't work correctly

    Quote Originally Posted by Norm View Post
    What values cause the timer to end? Print them out so you can see them.
    This is the function of the timer:
    private void startTimer(long time) {
        tiempoRestante = time;
        data.running = true;
        data.start = System.currentTimeMillis();
        reloj = new Timer(DELAY, (e) -> {
            updateTiempo();
            if (tiempoRestante <= 0) {
                reloj.stop();
                data.running = false;
                showImage();
            }
        });
        reloj.start();
    }
    But at the end I found the problem, when I was reading the JSON file, I was getting the start and remaining time as int and not as long:
    JSONTokener parser = new JSONTokener(new FileInputStream(file));
    JSONObject obj = new JSONObject(parser);
     
    // Incorrect
    data.start = obj.getInt("start");
    data.remaining = obj.getInt("remaining");
    // Correct
    data.start = obj.getLong("start");
    data.remaining = obj.getLong("remaining");

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Timer that could work when is closed doesn't work correctly

    I am glad you got it working.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Trying to get user input to work correctly
    By jcfor3ver in forum What's Wrong With My Code?
    Replies: 7
    Last Post: November 6th, 2013, 08:08 AM
  2. Program Works on NetBeans, but Jar file doesn't work correctly.
    By LeandroRodirgues in forum What's Wrong With My Code?
    Replies: 6
    Last Post: October 11th, 2013, 12:36 PM
  3. Can't Get Timer to Work, What Am I doing Wrong?!?!
    By Liikeaturtle in forum What's Wrong With My Code?
    Replies: 3
    Last Post: November 29th, 2012, 09:43 PM
  4. JLabel and set Location doesn't work correctly
    By Fantasy in forum AWT / Java Swing
    Replies: 6
    Last Post: November 15th, 2011, 12:02 PM
  5. I can't get this loop to work correctly
    By Nismoz3255 in forum Loops & Control Statements
    Replies: 1
    Last Post: February 27th, 2011, 04:20 PM

Tags for this Thread