swing: UI for a countdown timer - java

I need a variable countdown timer for between 1-10 seconds, that can be stopped and restarted. What's a good set of UI elements to use for this? I need something intuitive that uses a fairly small amount of screen real estate, comparable to a normal-sized JButton. A windup kitchen egg timer would be the best physical analogy:
NOTE: I know how to implement timers and restart them, I just need to figure out what UI elements to use.
NOTE 2: I need a variable countdown timer. If the user wants 1 second, I want a 1 second timer. If the user wants an 8.2 second timer, I want an 8.2 second timer. The kitchen timer above is simple, the user just turns it to a certain amount and lets it go.

Why not use a JProgressBar that starts off "full" and empties as the time decreases? You overlay the remaining time in seconds over the bar, therefore avoiding using additional screen real estate.

For a short term solution I used a JSlider... I add an ActionListener to its BoundedRangeModel, and set my timer when there is a change and the BoundedRangeModel.getValueIsAdjusting() returns false. When my timer counts down but is not yet expired and the BoundedRangeModel.getValueIsAdjusting() returns false, I call BoundedRangeModel.setValue().
Not too happy with it but it kinda does what I want.

A (ridiculously) simple solution: if you don't need too much graphical flair, just use a single JButton that displays the seconds remaining when the timer is running. When the timer's off, it displays "Start"; clicking it will begin the countdown. You could then stop (or pause) it by clicking when the timer is running.

It is fairly simple... Labels and buttons should be fine.. Here are some examples
(source: itblogs.info)
(source: softpedia.com)
(source: leancrew.com)

I'd use a JSpinner for the setting; a javax.swing.Timer for the counting; and a single button, labelled "Start" or "Stop" as a function of the Timer state. Almost anything would do for display, but #Adamski's JProgressBar idea has appeal.

Related

Timer in Greenfoot

I'm making a game right now and want to add a timer to count down to my end game screen, I can get the text to show up on my game screen but the numbers won't go down.
Any feedback would help!
Biased note: Greenfoot is a great tool to learn to program in Java. Keep going! But learn to read documentation[1], please.
You are calling subtractTime() only in the constructor Timer(). This way it will be called only once at creation time of your Timer object.
Call it in the act() method instead.
It will be called every time when the Greenfoot system lets all actors and the current world, well, act. The time between the calls is controlled by the "Speed" control below the world's frame, or by the specific methods of the class Greenfoot.
If you need "real-time" values like seconds, do some research how to obtain seconds or milliseconds.
[1]: You can read Greenfoot's documentation in the Editor window by double-clicking on "World" or "Actor" in the class diagram on the right.

How to use JLabel and Swing Timer to briefly notify the user?

I'm working on a small app for a class. One of the functions I want is when a button is clicked, it adds an object to an ArrayList based on the fields that they filled. When they click they button, I want them to have visual confirmation that the action has been performed. However, just updating a JLabel would cause it to sit there forever after the button was clicked.
I would like the label to start off displaying "".
When the button is clicked, I want it to say "Character Added!"
..for a few seconds. and then switch back to "".
I looked up some questions about label updating using a timer, but most of them have been using it to display a counting down clock, and they usually use a timer start method. I'm confused about if you need a timer stop method to reset the label.
Any pointers?
What I ended up doing is, instead of using a JLabel that updates, I simply made it so when the button is pressed and a character is added to the ArrayList, I called
JOptionPane.showMessageDialogue("Character Added!");
That way instead of a small little JLabel confirming it, they get a very apparent notification that requires them to acknowledge it. Tons more simple than doing the whole Timer thing.

want to drawLine additionally when Timer generates Events

As I wrote in title,
I want to drawLine additionally when Timer generates events.
Line will be draw like
first time;
ㅡ
second time;
ㅡ
ㅡ
I want line will be added on before's maintained situation
If first purpose cannot be done, (because I'm not good at Java yet, that's just my idea) I want to draw N line in Nth events then i redraw new N+1 line in (N+1)th events.
Which could be done in Java?
P.S. How to stop the Swing Timer?
You'll basically have to (not in order):
Build an event to happen on each tick of the timer
Pass it to a new timer (stopping the timer is in the documentation)
Set some sort of incrementing counter, either coordinate-based or tick-based
Override the paintComponent method in a component to draw the lines, based on the incrementing counter
From inside the event, call repaint() on your component (will happen on each timer tick)
Work on each one of those tasks individually, and when you feel you've mastered each one, you can try putting them all together.

Stop receiving all ActionEvents/Stop Listening in Java for a period of time?

I have a simple program that utilizes Java Swing Timer to display an image for 400 miliseconds, in this period of time I just want to stop all ActionListeners or stop taking ActionEvents. I've got 40+ buttons and want a simple way to do this.
Is there anyway to do that in Java?
Can you determine that you are in this "image displayed" state? The image goes up and you set the state to "image displayed" or whatever. Go through your widgets and decide which ones are supposed to be dead while the image is up. Turn them into Observers of this state value. When the state changes, they either enable or disable, as appropriate. The image code doesn't do anything directly to any widget. It just declares that the state is now "image displayed". It's up to the Observers to decide what to do, if anything, with that information.
Or use the GlassPane. That works too. Of course, the GlassPane shuts down everything. If you need to be more selective, you need a more fine-tuned approach.
You can use a temporary GlassPane instance to consume all events by registering empty listeners to it.
Use an undecorated modal JDialog to display the image. Before you make the dialog visible you would start a Timer. When the Timer fires in 400 ms you close the dialog.
I've had similar issues and typically found that its a design issue that got me in that situation. Being the case, I still had to find away around it. To fix the issue, I kept a list of the elements that I wanted to disable (stop listening) and iterated through them at the beginning and end of the timer. For buttons it should be as simple as:
for(Component c : listOfToggledComponents){
c.setEnabled(shouldItBeEnabled);
}
For buttons, this will grey out the button. Similar things happen to other swing components.

How to use a delay in a swing application

I am building a swing application. At some point, I have to start an "animation":
...
jpanel1.setBackground(Color.Black);
Delay(milli)
jpanel1.setBackground(Color.White);
...
and so on.
The gui itself and all the logic behind it work.It is just this time depended color-changing that does not. I have read, that swing is not thread safe, but all the examples I found showed me how to start another thread (for example in the background) but never how to stop the current swing-gui thread.
Edit:
The application should work as following:
configuration files are read, jframe is set up.
some simple questions are beeing asked
a dialogue is opened, which explains the animation.
after the user clicked "ok" the animation - some color flashing - is started. the color and the delay between the color-changing is depended on the configuration
another dialogue is opened and the programm continues -> new jpanel inside the jframe, buttons and so on.
the online thing that does not work are the delays between the color-changing. I understand now why it does not work and I am trying to build a timer, which activates a actionlister, which then changes the color and stops the timer... it just seems so much work for a simple delay... and I have to reorganize the entire animation in the application.
Take a look at: https://timingframework.dev.java.net/
and the samples that come in http://filthyrichclients.org/
They provide some very good information on how animation work and using the Timer framework. You'll have a good understanding of how it works.
I did a sample animation here with Swing after reading those:
count down demo app http://img580.imageshack.us/img580/742/capturadepantalla201004wd.png
Java application featuring blog.stackoverflow.com page ( click on image to see the demo video )
But I'm not even sure what is what you want to achieve.
EDIT
I read about the timing framework to understand better what is all about, but I actually didn't use it ( it is useful to create animations with no linear times - ie no every second as mine, but things like 1, 5, 3, 2 seconds )
The code I'm using in the demo above is exactly this:
final Timer imageTimer = new Timer();
imageTimer.schedule( new TimerTask() {
public void run() {
changeImage();
}
}, 0, 10000 ); //<-- every 10 seconds.
The animation for the "stackoverflowing" and the count down use a similar approach.
You do not want to stop the GUI thread, even if you want to have a flashing effect. This is because other basic actions, like repainting when the GUI is hidden by other windows, will be stalled. Take a look at Timer. It will allow you to have an event fired on an interval and you can handle that, in the GUI thread, in your actionPerformed method.
You will want to use the javax.swing.Timer class and not the java.util.Timer class.
The later is preferred when you need general timing the former is preferred for UI updating/changes.
See http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html
You may also want to look at https://timingframework.dev.java.net/.
Do the timer on another thread and when the timer goes off it can send an update message for the animation to draw the next frame.
Another consideration is the delay itself. Don't pick a fixed delay-interval. Old games used to do that and they become unplayable on faster computers. Instead what the newer games do is use the speed of the current CPU to figure out how many update events they need a second at runtime, call it a 'delay-factor', and is set when the program starts up. . The timer uses the delay factor so the animation displays correctly even on machines of different clock-speed.

Categories