JavaFX Timeline Include Minutes and Seconds - java

I have a Timer working with JavaFX but all it will count is seconds. How would I get it to do Minutes and Seconds.
timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.getKeyFrames().add(
new KeyFrame(Duration.seconds(1),
//new {
new EventHandler<ActionEvent>() {
// KeyFrame event handler
public void handle(ActionEvent event) {
remaining--;
// update timerLabel
timeStamp.setText(
remaining.toString());
if (remaining <= 0) {
timeline.stop();
}
}
}));
timeline.playFromStart();

Duration newValue=timeline.getCurrentTime();
int hTime = (int) newValue.toHours();
int minTime = (int) newValue.toMinutes();
int secTime= (int) newValue.toSeconds();
if(secTime/60>=1){ // this are to display later something like a clock 19:02:20
secTime%=60; //if you want just the time in minutes use only the toMinutes()
}
if(minTime/60>=1){
minTime%=60;
}
hTime = time in hours
minTime = time in minutes
secTime = time in seconds
usually the timeline works with millis so you have to be careful ;)

You Use getTime Method
http://docs.oracle.com/javafx/2/api/javafx/animation/KeyFrame.html
I think this will help you .

You may use java.util.concurrent.TimeUnit class which provides nice conversion facilities
int min = 3;
int sec = 14;
double totalSec = TimeUnit.MINUTES.toSeconds(min) + sec;

Related

Java countdown timer minutes and seconds

I have already written a 60 seconds countdown timer but I would like to transform this to have a minutes and seconds timer like mm:ss.
Can I rearrange this existing code to get that ?
Timer timer = new Timer();
TimerTask task = new TimerTask() {
int i = 60;
public void run(){
if (i >= 0) {
lab3.setText("Timer " + i--);
}
}
};
timer.scheduleAtFixedRate(task, 0, 1000);
You need to display remaining number of second i in format mimutes:seconds format. If you assume that there are always 60 seconds in a minute:
String time = String.format("%02d:%02d", i / 60, i % 60);
System.out.println(time);

Separate game loops for rendering and updating without built-in timers or separate threads

I am wondering if there is a way to update two different operations (in this case, updating and rendering) within a single thread / loop.
In my current scenario I have a TPS (ticks per second) that I want to have set to 64, and FPS (frames per second) that I want to be modifiable by the player.
The reason they cannot be in separate threads like I have been doing is because it causes a inconsistent flickering effect because of the timing between rendering and updating.
I am drawing with BufferStrategy and Canvas
This is what I was doing previously:
// The TPS = 64, the FPS = anything
public void init() {
tick_thread = new Thread(() -> {
long start, elapsed, wait;
while(alive) {
start = System.nanoTime();
input();
tick();
elapsed = System.nanoTime() - start;
wait = (1000 / TPS) - (elapsed / 1000000);
try {
Thread.sleep(wait <= 0 : 1 ? wait);
} catch(Exception e) {
e.printStackTrace(System.out);
}
}
});
render_thread = new Thread(() -> {
long start, elapsed, wait;
while(alive) {
start = System.nanoTime();
render();
elapsed = System.nanoTime() - start;
wait = (1000 / FPS) - (elapsed / 1000000);
try {
Thread.sleep(wait <= 0 : 1 ? wait);
} catch(Exception e) {
e.printStackTrace(System.out);
}
}
});
}
This works well, but I want to move from one thread to a single thread and still update them at a different rate. Like...
public void init() {
game_thread = new Thread(() -> {
long start, elapsed, wait, // etc
while(alive) {
// Some calculations
input(); // RUNS 64 TIMES A SECOND
tick(); // RUNS 64 TIMES A SECOND
render(); // Runs 30, 60, 120 times a second
// Some calculations
}
});
}
If you could help or try helping, it would mean a lot!

JavaFX animationTimer 144 fps

I have a problem and i can not find any solution to this problem.
I am using an animationTimer to update everything and i try to fix it on 60fps as it should do it by itself. The Problem is that on my first screen it runs on 144 fps and on my second with 60fps. I have a Gsync monitor as my first screen and i think because i force Gsync the animationTimer is fixed to 144fps. Is there any method to prevent the animationTimer go further 60fps?
AnimationTimer timer = new AnimationTimer() {
#Override
public void handle(long now) {
long elapsedNanosPerFrame = 0;
long oldFrameTime = frameTimes[frameTimeIndex] ;
double frameRate = 0;
frameTimes[frameTimeIndex] = now ;
frameTimeIndex = (frameTimeIndex + 1) % frameTimes.length ;
if (frameTimeIndex == 0) {
arrayFilled = true ;
}
if (arrayFilled) {
long elapsedNanos = now - oldFrameTime ;
elapsedNanosPerFrame = elapsedNanos / frameTimes.length ;
while () {
}
frameRate = 1_000_000_000.0 / elapsedNanosPerFrame ;
label.setText(String.format("Current frame rate: %.3f", frameRate));
label.setTextFill(Color.GREEN);
}
update(elapsedNanosPerFrame);
}
};
And yes it is not a visible Label bug or something, the gameplay is faster.

Using timer to repaint

I have a maze where robots can move around and explore. I'm trying to use the timer to repaint as the robot move but timer's not kicking in for some reason. It's not delaying the program so I can't see the repainting process. Here's my code:
public void updateDrawing(Maze maze) {
// 1000 millisecond delay
Timer t = new Timer(1000, new TimerListener(maze));
t.start();
}
private class TimerListener implements ActionListener {
private Maze maze;
public TimerListener(Maze maze) {
super();
this.maze = maze;
}
public void actionPerformed(ActionEvent e) {
maze.repaint();
}
}
public void explore (int id, Maze maze) {
visited.add(maze.getCell(row, col));
//Loop until we find the cavern
outerloop: //Label the outerloop for breaking purposes
while(!foundCavern){
//Move to a Cell
Cell validCell = chooseValidCell(maze);
//If validCell is null then we have to backtrack till it's not
if(validCell == null){
while(chooseValidCell(maze) == null){
//Go back in route till we find a valid cell
Cell lastCell = route.pollLast();
if(lastCell == null){ //Implies we didn't find cavern, leave route empty
break outerloop;
}
this.row = lastCell.getRow();
this.col = lastCell.getCol();
updateDrawing(maze); // <- this calls repaint using timer
}
//Add back the current location to the route
route.add(maze.getCell(row, col));
validCell = chooseValidCell(maze);
}
this.row = validCell.getRow();
this.col = validCell.getCol();
updateDrawing(maze); // <- this calls repaint using timer
//Add to the route
route.add(validCell);
//Add to visited
visited.add(validCell);
//Check if we're at the cavern
if(row == targetCavern.getRow() && col == targetCavern.getCol()){
foundCavern = true;
}
}
}
Can anyone tell me why? Thank you!
try use not ** updateDrawing(maze)** but this method:
void updateMaze() {
EventQueue.invokeLater(()->updateDrawing(maze));
}
Here's how to make a basic timer.
All you need to do to calculate the time to display, is to record the time that the timer started:
long startTime = System.currentTimeMillis();
Later, when you want to display the amount of time, you just subtract this from the current time.
long elapsedTime = System.currentTimeMillis() - startTime;
long elapsedSeconds = elapsedTime / 1000;
long secondsDisplay = elapsedSeconds % 60;
long elapsedMinutes = elapsedSeconds / 60;
//put here code to format and display the values
You can make your program wait until elapsedSeconds == whatever value you want.
From Make a simple timer in Java

timer with 10milli second resolution android

I am trying to display a countup timer with format 1.00 resolution. basically seconds and with hundredths of second or 10ms resolution.
I have tried the chronometer function but still no luck, it seems it can only track 1 second resolution.
here is some of my code:
public void stopwatch() {
stopWatch.setOnChronometerTickListener(new OnChronometerTickListener(){
#Override
public void onChronometerTick(Chronometer arg0) {
countUpmilli = (Long) ((SystemClock.elapsedRealtime() -arg0.getBase())/ 100);
countUpSec = (Long) ((SystemClock.elapsedRealtime() -arg0.getBase()) / 1000);
//asText = (countUp / 60) + ":" + (countUp % 60);
asText = (countUpSec / 1) + "." + (countUpmilli%100);
timertext.setText(asText);
}
});
stopWatch.start();
}
I think you have to use System.nanoTime();

Categories