A
A
Alexander2015-06-15 19:34:07
Java
Alexander, 2015-06-15 19:34:07

How to create Java application without GUI?

Wrote a simple application:

package program;
public class Program {
    javax.swing.Timer dynTimer;
    
    public static void main(String[] args) {
        Program p = new Program();
        p.init();
        p.start();
    }

    private void init() {
        System.out.println("> Инициализация");
        dynTimer = new javax.swing.Timer(100, (java.awt.event.ActionEvent e) -> {
            update(e.getWhen());
        });
    }

    private void start() {
        System.out.println("> Запуск");
        dynTimer.start();
    }

    private void update(long when) {
        System.out.println("Событие: " + when);
    }
}

when run, only this is output:
run:
> Инициализация
> Запуск
СБОРКА УСПЕШНО ЗАВЕРШЕНА (общее время: 0 секунд)

and that's it ... but where did the timer go? Why did he never tick? Why doesn't the app stay running until I force close it or stop the timer? How to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
pi314, 2015-06-15
@wxmaper

public class Aaa {

    javax.swing.Timer dynTimer;
    public long startTime;
    public static boolean running = true;

    public static void main(String[] args) {
        Aaa p = new Aaa();
        p.init();
        p.start();
        
        while (running) {
            try {
                Thread.sleep(100);
                System.out.println("::: " + running);
            } catch (InterruptedException ie) {
                System.out.println("Child thread interrupted! " + ie);
            }
        }
    }

    private void init() {
        System.out.println("> Инициализация");
        dynTimer = new javax.swing.Timer(100, (java.awt.event.ActionEvent e) -> {
            update(e.getWhen());
        });
    }

    private void start() {
        System.out.println("> Запуск");
        dynTimer.start();
        startTime = new java.util.Date().getTime();
    }

    private void update(long when) {
        System.out.println("Событие: " + (startTime + 1000) + " : " + when + " : " + running);
        if(startTime + 1000 < when) {
        	dynTimer.stop();
        	running = false;
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question