Stopping a Swing timer until the user clicks - java

I'm writing a card game. Right now I'm having problems with mouse handling. Below is the timer that handles the game flow of drawing and discarding cards.
final Timer timer = new Timer(1000, null);
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
b.players[p].drawCard();
if(p==0) // player zero is the human player
{
timer.stop();
// ...
b.players[p].discardCard(i);
timer.start();
}
else
b.players[p].discardCard(0);
p=(p+1)%4;
b.repaint();
}
});
The thing is that I want to stop the timer, wait until the user clicks the card he wants to discard, then start the timer again. b implements MouseListener in a basic way:
public void mouseClicked(MouseEvent arg0)
{
clickX = arg0.getX();
clickY = arg0.getY();
}
There's also the xYtoCardIndex() method somewhere out there.
What do I do here? I assume I have to do nothing in a nonblocking way, right?

In pseudo-code, in your MouseEventListener :
public void mouseClicked(MouseEvent arg0)
{
clickX = arg0.getX();
clickY = arg0.getY();
Card discarded = getCard(clickX,clickY);
b.players[p].discardCard(discarded);
// The card has been discarded, I can start my timer again.
timer.start();
}
In your drawCard function :
public void drawCard() {
// Stop the timer
timer.stop();
// Do the drawing.
}
This way, when the player draws a card, the timer stops until a card is discarded.

First, your code is not compiled:
b.players[p].discardCard(int i); contains a syntax error int i.
Second, I do not really understand the problem. Stop the timer when you want, implement your listener (i.e. mouse listener) that starts the timer.
Or probably I did not understand your question?
BTW I have just checked Timer API. It does not have neither start nor stop methods. You have to deal with specific tasks to control execution.

Related

JAVA SWING - Creating Animation using Swing Timer

I am trying to setup a program that enables the user to display a transition when clicking the next and previous button. When pressing next, the swing timer should trigger and start the animation. When transitioning, there should be a flag that states it is in the transition period. The Swing timer should fire once every tenth of a second and essentially last 1 second.
public class guiCreation {
static Timer timer;
static boolean flag = false;
private static void guiInterface() {
next.addActionListener(new ActionListener(){
timer = new Timer(1000, this);
public void actionPerformed(ActionEvent e){
nextGest();
}
});
//should go to the next tab
previous.addActionListener(new ActionListener(){
//if the list gets to the beginning, disable button
public void actionPerformed(ActionEvent e){
prevGest();
}
});
}
public static void nextGest() {
timer.start();
previous.setEnabled(true);
next.setEnabled(true);
//if the list gets to the end, disable button
if (cardLayout.isNextCardAvailable()) {
status.setText(" Next button has been clicked");
//System.out.println("This is the" + size);
cardLayout.next(cardPanel);
next.setEnabled(cardLayout.isNextCardAvailable());
}
}
public static void prevGest() {
if (cardLayout.isPreviousCardAvailable()) {
timer.start();
next.setEnabled(true);
previous.setEnabled(true);
status.setText(" Previous button has been clicked");
cardLayout.previous(cardPanel);
previous.setEnabled(cardLayout.isPreviousCardAvailable());
}
}
}
This: "The Swing timer should fire once every tenth of a second ..." -- does not agree with this: timer = new Timer(1000, this); Your Timer is firing once every second, not every 10th of a second.
Instead, you should:
Create a new Timer(100, ...), one that fires every 10th of a second
Store in an instance field the start time in msecs when the Timer begins (likely do this in your button's ActionListener)
Within the Timer's ActionListener get the current mSecs and use this to check the elapsed time
Stop the Timer via ((Timer) e.getSource()).stop(); once 1 full second has elapsed
No need for a flag, since all you need to do is to check if the Timer isn't null and if it .isRunning(). e.g., if (timer != null && timer.isRunning()) { -- then the animation is proceeding.
Unrelated suggestion:
Get out of the static world and into the instance world. You're programming in Java, a language that is built to use OOPs from the ground up, and you don't want to fight against the OOPs paradigm.

Reuse a timer timertask Java

Soo created a timer using extending timertask.
label_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
label_1.setVisible(false);
label_2.setVisible(true);
timer.purge();
class MyTimeTask extends TimerTask
{
public void run(){
genReelNumbers();
laa++;
if(laa==50){
timer.cancel();
timer.purge();
laa=0;
label_1.setVisible(true);
label_2.setVisible(false);}}}
timer.purge();
timer.schedule(new MyTimeTask(), 0, 50);}});
But im getting a error with the timer already canceled! As you can see i already tried to use the purge(), soo it cancels the "canceled" timers (dont know if that does make any sence). I want to use this timer each time that i press on the label! Any ideas?
First and foremost, this looks to be a Swing application, and if so, you shouldn't be using java.util.Timer and java.util.TimerTask since Swing is single-threaded, and the two classes above create a new thread or threads to achieve their actions, meaning that important code that should be called on the Swing event thread will not be called on this thread. This this risks causing pernicious intermittent and hard to debug threading exceptions to be thrown. Instead use a javax.swing.Timer. Then to stop this timer, simply call stop() on it, and to restart it, simply call start() on it. For more on this, please read: How To Use Swing Timers.
For example, I'm not 100% sure what you're code is supposed to be doing, but it could look something like:
// warning: code not compile- nor run-tested
label_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
label_1.setVisible(false);
label_2.setVisible(true);
// assuming a javax.swing.Timer field named timer
if (timer != null && timer.isRunning()) {
// if the timer is not null and it's running, stop it:
timer.stop();
}
// TIMER_DELAY is an int constant that specifies the delay between "ticks"
timer = new Timer(TIMER_DELAY, new ActionListener() {
#Override // this method will be called repeatedly, every TIMER_DELAY msecs
public void actionPerformed(ActionEvent e) {
genReelNumbers();
laa++;
if(laa==50){
timer.stop();
// timer.purge();
laa=0;
label_1.setVisible(true);
label_2.setVisible(false);
}
}
});
timer.start();
}
});
after canceling the timer you have no other choice than creating a new object....
I followed the #Hovercraft advice and changed to javax.swing.Timer
It turned out like this:
//The variable "taxa" is the amount of times that i want it to do the task
javax.swing.Timer time1 = new javax.swing.Timer(taxa, new ActionListener() {
public void actionPerformed(ActionEvent e) {
genReelNumbers();
}
});
//starts the timer
time1.start();
//New timertask
TimerTask tt = new TimerTask() {
#Override
public void run() {
//stops the timer
time1.stop();
label_2.setVisible(false);
label_1.setVisible(true);
verificarodas();
}
};
Timer time = new Timer(true);
// the 2000 is how long i want to do the task's
//if i changed to 3000 it would take 3 seconds (remember it has to be a value on miliseconds) to do the 15 times, and soo on
time.schedule(tt, 2000);

Java Swing timer does not do what I want it to

I need to write a program that uses a swing countdown timer to do something (in this case, print out a String in the console). It gets the needed delay info from a spinner and executes the code when I hit the Start button. However, when I enter a value in the spinner, it just waits for twice that many seconds and finishes the run without printing out anything.
private void StartActionPerformed(java.awt.event.ActionEvent evt) {
int x = (int) Spinner1.getValue() * 1000;
Timer TIMER = new Timer(x, new MyActionListener());
TIMER.start();
try {
Thread.sleep(x * 2);
} catch (InterruptedException e) {
}
TIMER.stop();
}
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Something");
}
}
Any help would be greatly appreciated!
The problem is that you are locking out yourself.
With
Thread.sleep(x * 2);
you are blocking the EventDispatchThread that would run your ActionListener. Still the timer internally keeps a flag that the timeout occured and that it should run your ActionListener at the next possible time.
But
TIMER.stop();
is resetting the TIMER, so that the notification is lost.

Java - Trigger swing timer with a mouseEvent?

I'm trying to turn on the timer using mouseEntered event with MouseListener it doesn't seem to work. Am i doing somthing wrong? I'm new to Java. Thanks in advance!
int counter = 0;
Timer timer = new Timer(1000,this);
public void mouseEntered(e MouseEvent)
{
if(e.getComponent == mouseEnteredArea)
{
timer.start()
counter++;
if(counter == 10)
{
timer.stop();
}
}
}
What's happening is when the mouse enters the area, your code starts the timer, adds one to counter (so counter == 1), checks if counter is equal to 10. Since it isn't, the code then skips the if statement and exits the method.
It's difficult to tell your actual intentions from that question, so if that wasn't enough to help, please explain what you're trying to do.
I think you may not understand how the timer works. Basically the timer has an ActionListener. Every 1000 milliseconds (in your case), the actionPerformed will be called. So I believe the code you have above should be in the ActionListener, and just call timer.start() in the mouse method. Something like.
Timer timer = new Timer(1000, new ActionListener(){
private int counter = 0;
#Override
public void actionPerformed(ActionEvent e) {
if (counter == 10) {
((Timer)e.getSource()).stop();
counter = 0;
} else {
System.out.println("Count: " + (++counter));
}
}
});
....
#Override
public void mouseEntered(MouseEvent e) {
timer.start();
}
Resources
How to Use Swing Timers
How to Write a Mouse Listener

Java: Double-Click a JSlider to Reset

I have a JSlider that sets the speed of my metronome, from 40 - 200, where 120 is the default, in the middle.
When the user clicks the metronome button, the metronome plays at the speed displayed on the JSlider - the user drags the slider to the right, the speed of the metronome increases, and it decreases if they slide it to the left.
How do I add functionality so that if the user double-clicks on the JSlider button, it defaults back to 120 - in the middle?
Here is my code:
public Metronome() {
tempoChooser = new JSlider();
metronomeButton = new JToggleButton();
JLabel metText = new JLabel("Metronome:");
add(metText);
...
tempoChooser.setMaximum(200);
tempoChooser.setMinimum(40);
tempoChooser.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
tempoChooserStateChanged(evt);
}
});
add(tempoChooser);
...
}
private void tempoChooserStateChanged(javax.swing.event.ChangeEvent evt) {
final int tempo = tempoChooser.getValue();
if (((JSlider) evt.getSource()).getValueIsAdjusting()) {
setMetronomeButtonText(tempo);
} else {
processTempoChange(tempo);
}
}
thanks in advance!
This should help you out: http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html
You need to read up on that and implement MouseListener. You can use int getClickCount() to count how many times the user has clicked, which will help you read double clicks.
Hope this helps!
Even though I dont see a question, my gues is you are looking for MouseListener.
Not simple job, you have to add javax.swing.Timer and listening if during fixed period Mouse cliked once or twice times, for example
I recently wrote something similar so I could differentiate between single and double left mouse-button clicks:
private Timer timer;
#Override
public void mouseClicked(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1){
if (timer == null) {
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() { // timer expired before another click received, therefore = single click
this.cancel();
timer = null;
/* single-click actions in here */
}
}, (Integer) Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval"));
}
else { // received another click before previous click (timer) expired, therefore = double click
timer.cancel();
timer = null;
/* double-click actions in here */
}
}
}

Categories