I am trying to add a timer in my screen recording application being developed using JavaFX (IDE: NetBeans) and OS (Win 10). I am adding a timer now, which is to be used as:
User clicks on start recording, A Label on my application should start showing the time as 00:00:00, I have the time in seconds which is being printed on console even but when I use it to be displayed on application it just shows 0 Seconds. I am attaching code too. Kindly help. How can I refresh app interface or run timer when I have the value, It is just not updating.
Here you can see my app doesn't start timer; however, is being printed on consoleApp's Snap Console Snap
private void scheduleTimerTasks() {
isRecording = true;
int delay =50;
long period = 500;
//1000 / 48;
RecordTimer.reset();
timerRecord = new Timer("Thread TimerRecord");
timerCount = new Timer("Thread TimerCount");
recorderTask = new ScreenRecorderTask(encoder, rectangle);
countTask = new TimerCountTask(Timer);
timerRecord.scheduleAtFixedRate(recorderTask, delay, period);
timerCount.scheduleAtFixedRate(countTask, delay, period);
Timer.setText(""+countTask.timeInSec+" s"); //Setting Label Text
System.out.println(countTask.timeInSec);
recordStateLabel.setText("recorder Started...");
}
You could use AnimationTimer from javafx.animation.animationTimer, the handle' method of this timer will be called every frame.
Related
I am trying change the image LayoutX and LayoutY positions ever 1 second. But I cant find any (timer) method suitable for this. I am looking for something similar to the JavaScript "setInterval" that simply lets me create a "timer cycle" using Java or JavaFX.
Any advice are widely appriciated!
With java.util.Timer you can schedule such a task.
The method timer.schedule() executes a task only ones. To repeat your task
use the method timer.scheduleAtFixedRate().
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
System.out.println("hello");
}
}, 1000, 1000);
The second parameter of scheduleAtFixedRate() is the delay before the first execution in milliseconds and the last parameter is the interval between the tasks being executed in milliseconds.
You can use a Timeline with INDEFINITE cycle count for this purpose.
Example:
Timeline tl = new Timeline(new KeyFrame(Duration.seconds(1), evt -> {
// toggle image postion
imageView.setLayoutX(200 - imageView.getLayoutX());
imageView.setLayoutY(200 - imageView.getLayoutY());
}));
tl.setCycleCount(Animation.INDEFINITE);
tl.play();
This guaranties the event handler runs on the JavaFX application thread.
This snippet of code essentially reveals the back side of the cards when clicked. The showFace function sets the icon and text and therefore implying the front of the card. Light gray background is the back. If a non matching card is clicked, I first intend to showFace for a brief moment ( 2 seconds) than revert to the "back side of the card." However, upon clicking a non matching card, the icon and text flashes instantaneously and reverts to its gray background.
Tried changing the 2000 milliseconds to something higher but no avail. Any help is appreciated.
else if (currentMode == 1){
//matched cards
if(checkCards(currentCard, names)){
showFace();
currentMode = 0;
currentCard = "";
deafTo(this);
}
//else non match, still checking mode
else{
showFace();
var timer: Timer = null;
val action = new ActionListener(){
override def actionPerformed(event : ActionEvent){
icon = null;
text = "";
background = Color.DARK_GRAY;
timer.stop();
}
};
timer = new Timer (2000, action);
timer.setInitialDelay(0);
timer.start();
}
}
def showFace()={
text = names;
horizontalTextPosition = Alignment.Center;
verticalTextPosition = Alignment.Bottom;
background = Color.WHITE;
val icons = new ImageIcon(path);
val newIc = icons.getImage();
val newIcons = newIc.getScaledInstance(100, 75,
java.awt.Image.SCALE_SMOOTH);
icon = new ImageIcon(newIcons);
repaint();
}
This is because you set an initial delay of 2000ms in the constructor
timer = new Timer(2000, action)
But then you overwrite it to 0ms by:
timer.setInitialDelay(0);
Remove this line and you should be good.
You can check here Swing Timer API.
And see some examples here.
Javadoc http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html
This class does not offer real-time guarantees: it schedules tasks using the Object.wait(long) method.
Java 5.0 introduced the java.util.concurrent package and one of the concurrency utilities therein is the ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer/TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.
I have a Java Swing timer which updates a label every second. After starting the timer, the label is updated every second and everything works well.
Then after a random time interval, which changes from execution to execution, the label stops being updated. I've put a breakpoint in the timer update code and it no longer gets triggered.
I've also put log statements in all the places where I would normally stop the timer, but none of those places are called.
What could be the problem?
EDIT: Here is the sample of the code
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent arg0) {
secondsRemaining--;
System.out.println("Seconds remaining:" + secondsRemaining);
//update the progressbar
double initialLength = currentSettings.getLength()*60;
double progress = (initialLength - secondsRemaining)/initialLength ;
progressBarTime.setProgress(progress);
//update the progress label
progressPercentage.setText(((int)(progress * 100)) + "%");
if (secondsRemaining >= 0) {
updateTimeRemaining(secondsToString(secondsRemaining));
} else {
System.out.println(">0 seconds TIMER STOPPED with the number of seconds = " + secondsRemaining);
treatmentTimer.stop();
// set the status to Finished
currentState = State.FINISHED;
}
}
}
And the timer initialization:
tTimer = new Timer(1000, actionListener);
tTimer.start();
What's strange is that the program works fine on a PC with JRE 7u7 installed, i.e. the timer updates the label successfully, but I've tried on two PCs with 7u10 and this timer stopping issue happens on both.
Exception might be thrown, use try catch or Use UncaughtExceptionHandler to trace.
So I think I solved the problem. The garbage collector was removing the timer instance, for some unknown reason. I put a
System.out.println("message");
Inside the actionlistener of the timer, so that it would not be garbage collected.
I'm looking for the best way to do the following. If someone could point me in the right direction I'd be greatfull.
I have 5 buttons,
Button 1
Button 2
Button 3
Button 4
Button 5
What I'd like to happen is every 5 seconds the focus of the button move one down. So the app starts and Button 1 has focus. Then 5 seconds later button 2 takes focus and so on so on until Button 5 and then back to Button 1. When I say focus I mean that if the space bar was pressed the button would be pressed. Any assistance would be appreciated. Thanks
You could use a java swing timer for this task. Take a look at the example in oracle docs
http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html
You can use the KeyboardFocusManager for this as well. Sample code below using Timer object from java.util. The code below changes focus every 500 ms.
final KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
manager.focusNextComponent();
}
}, 0, 500);
Hope this helps.
You can create thread that sleeps for 5 senconds, then awakes and sets focus to the next button. Store your buttons in array.
final int n = 5;
final int TIMEOUT = 5000;
Button[] buttons = new Button[n];
// fill the array
new Thread() {
for (i = 0; ; i < n ? i++ : i = 0) {
buttons.requestFocusInWindow();
try {
Thread.sleep(TIMEOUT);
} catch(InterruptedException e) {}
}
}.start();
You can also use java.util.Timer
I want to create a simple clock using Java. The code is so simple that I will give an example:
for(int i=0;i<=60;i++)
jLabel11.setText( Integer.toString(i) );
The problem is while I'm running my program the result didn't show each update in sequence.
It show only the 60 digit immediately, without showing the change from 1 to 2 to 3 ...
How can i fix this problem?
The problem is that changes to the UI should run on the event dispatch thread, but blocking this loop (and blocking the UI) will stop the screen from repainting. Instead, use a timer to perform regular updates, e.g.
Timer timer = new Timer();
ActionListener updater = new ActionListener()
{
int count;
public void actionPerformed(ActionEvent event) {
jLabel11.setText( Integer.toString(count++) );
if (count==60)
timer.stop();
}
}
timer.setDelay(100);
timer.addActionListener(updater);
timer.start();
See the Sun Tutorial - How to use Swing Timers.