Baiscilly, I'm making this game for a project, and I can't fiure out how to get timers to work whatsoever, here is my code attempting.
import java.awt.event.*;
import java.util.Timer;
public class Timers {
private int timeLeft = 60;
private void timer() {
while(timeLeft > 0){
int delay = 1000;
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
timeLeft--;
}{
new Timer(delay, taskPerformer).start();
};
};
}
}
}
I don't know what I'm doing wrong or what to do next. As well as this i need to make an Actionlistener see if the users answer is the same as the preset answer.
import javax.swing.*;
import java.awt.event.*;
...
JTextField Janswer = new JTextField();
Janswer.setBounds(110, 70, 150, 25);
newFrame.add(Janswer);
if Janswer = equations.getanswer(){
score++;
And I guess if i'm giving this much I may as well give you where it is getting the answers from
public class Equations {
private static String equation;
private int answer;
Problems problem = new Problems();
public Equations() {
equation = problem.getFirstNumber() + " " + problem.getSign() + " " + problem.getSecondNumber();
String sign = problem.getSign();
if (sign.equals("+"))
answer = problem.getFirstNumber() + problem.getSecondNumber();
else if (sign.equals("-"))
answer = problem.getFirstNumber() - problem.getSecondNumber();
else if (sign.equals("*"))
answer = problem.getFirstNumber() * problem.getSecondNumber();
}
public static String getEquations() {
return equation;
}
public int getAnswer() {
return answer;
}
}
Thank you all for any help you're able to give me, and just let me know if I need to change my post in any way, I'm new to this!
The main problem is you are using a while-loop, which is creating a bunch of new Timers on each iteration, which are all decrementing the timeLeft value. You only need a single Timer.
Depending on what you want to do, you could do something like...
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Time's up!");
}
};
new Timer(60 * 1000, taskPerformer).start();
This will establish a call back in 1 minutes time, which can allow you to define a timeout...
Know, if you want a count down timer, you could do something like...
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
count++;
if (count >= 59) {
((Timer)evt.getSource()).stop();
System.out.println("Time's up!");
}
}
};
new Timer(1000, taskPerformer).start();
Which basically counts to 60 (from 0) and is updated every second (you'd have to use 60 - count to get the count down value)...
See How to use Swing Timers for more details
Related
I'm trying to make a simulation of a roulette game using GUI/Swing for my upcoming exam. I have two classes, one is called GUI and is actually the code used for the components, such as JFrame, JOptionPane, JButtons etc. The other one extends Thread and is supposed to show random numbers on a small JLabel, and the run method goes something like this:
public void run() {
int k = 0;
for (int i = 0; i < 50; i++) {
k = (new Random().nextInt(37));
label.setText(k + " ");
label.setFont(new Font("Tahoma", Font.BOLD, 56));
label.setForeground(Color.yellow);
try {
sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
And in the GUI class I just want to TAKE the number from the last iteration of the above loop, and then pass it to a new int, which I'm going to use later in the GUI class.
Any ideas?
Use Swing Timer instead of Thread.sleep that sometime hangs the whole swing application.
Please have a look at How to Use Swing Timers
Timer timer = new Timer(50, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//next call from here
}
});
timer.setRepeats(false);
timer.start();
I just want to TAKE the number from the last iteration of the above loop, and then pass it to a new int, which I'm going to use later in the GUI class.
Just create a method (setter) in another class that accepts int and call it from this class for last call.
Sample code:
private int counter = 0;
private Timer timer;
...
final JLabel label = new JLabel();
label.setFont(new Font("Tahoma", Font.BOLD, 56));
label.setForeground(Color.yellow);
Thread thread = new Thread(new Runnable() {
public void run() {
timer = new Timer(50, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (counter++ < 50) {
int k = (new Random().nextInt(37));
label.setText(k + " ");
} else {
timer.stop();
label.setText("next call");
}
}
});
timer.setRepeats(true);
timer.start();
}
});
thread.start();
snapshot:
I have problem that I don't understand, how to correctly use the Java timer with JButton.
The idea of what I need -
When I click on JButton with text "0" then starts the timer counting from two seconds till zero.
When button is released program checks the situation:
if timer now is 0 then it shows in JTextField sign "+", else it shows "0".
Here is my code of program. Can someone please add the things that I need to make the program work like the idea I want?
public class DialPanel extends JPanel {
private MainFrame frame;
public DialPanel(MainFrame frame) {
this.frame = frame;
this.setLocation(0, 90);
this.setSize(300, 290);
this.setLayout(null);
this.setBackground(color);
this.initContent();
}
// -------------------------------------------------------------------------
private JButton btnNumZero;
private JTextField txfNumber;
private void initContent() {
txfNumber = new JTextField();
this.add(txfNumber);
txfNumber.setSize(190, 30);
txfNumber.setLocation(30, 0);
txfNumber.setFocusable(false);
txfNumber.addActionListener(controller);
btnNumZero = new JButton();
this.add(btnNumZero);
btnNumZero.setText("0");
btnNumZero.setFocusable(false);
btnNumZero.setSize(30, 30);
btnNumZero.setLocation(10, 10);
btnNumZero.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
//Start someTimer countdown from two seconds
}
});
btnNumZero.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
//Stop someTimer
//if someTimer == 0 seconds then do this line:
txfNumber.setText("+");
//else do this line:
txfNumber.setText("0");
}
});
}
}
Excuse me if there is some unnecessary error with code. I deleted and changed a lot of things from the real one code so that this could be more understandable and clear for reading.
Instead of using a Timer, you may want to just make use of System.currentTimeMillis(). The Timer may not be a timer in the sense you are looking for, as a stopwatch type object.
You could do something like this
long startTime;
long endTime;
btnNumZero.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
startTime = System.currentTimeMillis();
}
});
btnNumZero.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
endTime = System.currentTimeMillis();
long difference = endTime - startTime;
if (difference > 2000)
txfNumber.setText("+");
else
txfNumber.setText("0");
}
});
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Stop timer with conditional only works first time?
I'm very confused as to how to make a timer using the swing and not util timer.
I am making a game where users have to answer questions in a 30 second time limit. I have a PlayFrame, where the time is shown, and a method inside PlayFrame called startTimer which contains all the timer stuff.
public static void startTimer() {
int elapsedSeconds = 0;
javax.swing.Timer myTimer = new javax.swing.Timer(1000, new MyTimerActionListener());
elapsedSeconds++;
if (elapsedSeconds == 30) {
myTimer.stop();
timerLabel.setText("0");
wrong();
} else {
String text = String.format("f", 30 - elapsedSeconds);
timerLabel.setText(text);
}
if (myTimer != null && myTimer.isRunning()) {
myTimer.stop();
myTimer = null;
timerLabel.setText("0");
} else {
elapsedSeconds = 0;
myTimer = new javax.swing.Timer(1000, new MyTimerActionListener());
myTimer.start();
String text = String.format("t", 30);
timerLabel.setText(text);
}
}
What I want this method to do is have a timer that counts down from 30 until the question is answered correctly. If the answer is answered incorrectly I want the timer to stop.
For an answer perhaps some psuedocode (or real code) to move me in the right direction. And this is for personal use, not homework or anything.
Please remember that this is a part of my whole code and it needs to work with other parts of it. I'll give more information upon request, thanks!
EDIT: New startTimer() method NOTE all System.out.print is for testing only:
public static void startTimer() {
class TimerListener implements ActionListener {
Timer timer = new Timer(1000, new TimerListener());
int elapsedSeconds = 30;
String seconds = Integer.toString(elapsedSeconds);
#Override
public void actionPerformed(ActionEvent evt) {
timer.start();
if (elapsedSeconds == 0) {
//System.out.print("here");
timer.stop();
PlayFrame.wrong();
}
else{
//System.out.print("hersfde");
elapsedSeconds--;
PlayFrame.timerLabel.setText(seconds);
}
//System.out.println(elapsedSeconds);
}
}
//System.out.print("l");
}
Doesn't do anything and not sure why.
This is how I would make a countdown timer:
Timer timer = new Timer(1000, new TimerListener());
class TimerListener implements ActionListener{
int elapsedSeconds = 30;
public void actionPerformed(ActionEvent evt){
elapsedSeconds--;
timerLabel.setText(elapsedSeconds)
if(elapsedSeconds <= 0){
timer.stop();
wrong()
// fill'er up here...
}
}
}
Okay, so basically what I'm trying to create a timer that counts up and down. I need the program to activate just one timer at any one time. There are two timers, one causing a variable to increment, the other to decrement. I can't seem to get it right, when I press the increment, the variable increments but never stops, even when I press the decrement button. How do I go about doing this? Also, another quick question : How do I return a value which is within a keypress method? Keypress are by default void, so I stumped.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class TimerTutorial extends JFrame {
JLabel timerLabel;
JButton buttonAdd, buttonMin, buttonReset;
Timer timer;
Timer timer2;
public TimerTutorial() {
setLayout(new GridLayout(2, 2, 5, 5));
buttonReset = new JButton("Press to reset");
add(buttonReset);
buttonAdd = new JButton("Press to Add");
add(buttonAdd);
buttonMin = new JButton("Press to Minus");
add(buttonMin);
timerLabel = new JLabel("Waiting...");
add(timerLabel);
event e = new event();
buttonAdd.addActionListener(e);
buttonMin.addActionListener(e);
}
public class event implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonAdd) {
TimeClassAdd tcAdd = new TimeClassAdd();
timer = new Timer(1000, tcAdd);
timer.start();
} else if (e.getSource() == buttonMin) {
TimeClassMin tcMin = new TimeClassMin();
timer2 = new Timer(1000, tcMin);
timer2.start();
} else if (e.getSource() == buttonReset) {
timer.stop();
timer2.stop();
// This code does not work
// Need to revert counter to 0.
}
}
}
public class TimeClassAdd implements ActionListener {
int counter = 0;
public void actionPerformed(ActionEvent f) {
String status_symbol[] = new String[4];
status_symbol[0] = "Unused";
status_symbol[1] = "Green";
status_symbol[2] = "Yellow";
status_symbol[3] = "Red";
if (counter < 3) {
counter++;
timerLabel.setText("Time left: " + status_symbol[counter]);
} else {
timerLabel.setText("Time left: " + status_symbol[counter]);
}
}
}
public class TimeClassMin implements ActionListener {
int counter = 4;
public void actionPerformed(ActionEvent d) {
String status_symbol[] = new String[4];
status_symbol[0] = "Unused";
status_symbol[1] = "Green";
status_symbol[2] = "Yellow";
status_symbol[3] = "Red";
if (counter >= 3) {
counter = 3;
timerLabel.setText("Time left: " + status_symbol[counter]);
counter--;
} else if (counter == 2) {
timerLabel.setText("Time left: " + status_symbol[counter]);
counter--;
} else if (counter == 1) {
timerLabel.setText("Time left: " + status_symbol[counter]);
}
}
}
public static void main(String args[]) {
TimerTutorial gui = new TimerTutorial();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(500, 250);
gui.setTitle("Timer Tutorial");
gui.setVisible(true);
}
}
In case you start the second timer you will definitively have to stop the first one if it is still running (i.e. call timer2.stop() just before timer.start() and the other way round).
Otherwise both will interfere, i.e. they access the same fields (in this case the timerLabel). Depending on the timing this might then look like if the second timer is continuously increasing the value. If e.g. the increase timer is always triggered shortly after the decrease timer, the output value will always be 3 - Red. The counter itself is not increased but the label is filled with this value over and over again and thus looks like it is ignoring the decreasing timer completely.
Nevertheless you should also stop each timer if its counter has reached the final value. There is no need to let it run any longer.
Regarding your second question: You cannot assign a return value but instead modify some field of your listener which you can then access outside of the action method.
One other problem: your reset button (or any button for that matter) won't do anything if you don't add an actionListener to it. In other words, you need to have code that looks like...
buttonReset.addActionListener(...);
somewhere in your program's code for the button to work.
I need this timer program to run indefinately, until someone presses the reset button. This timer program would increment or decrement with a single click of a button. For example, click once, and it will increment UNTIL someone says it to stop, or to decrement. Problem is, I think i've made the correct codes for this, but it simply wont run. There must be a logical error in it, can't seem to pinpoint where exactly, though. Can you tell whats wrong with my code?
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class TimerTutorial extends JFrame {
JLabel timerLabel;
JButton buttonAdd, buttonMin, buttonReset;
Timer timer;
Timer timer2;
public TimerTutorial() {
setLayout(new GridLayout(2, 2, 5, 5));
buttonReset = new JButton("Press to reset");
add(buttonReset);
buttonAdd = new JButton("Press to Add");
add(buttonAdd);
buttonMin = new JButton("Press to Minus");
add(buttonMin);
timerLabel = new JLabel("Waiting...");
add(timerLabel);
event e = new event();
buttonAdd.addActionListener(e);
buttonMin.addActionListener(e);
buttonReset.addActionListener(e);
}
public class event implements ActionListener {
public void actionPerformed(ActionEvent e) {
while (true) {
TimeClassAdd tcAdd = new TimeClassAdd();
timer = new Timer(1000, tcAdd);
timer.start();
timerLabel.setText("IT HAS BEGUN");
}
}
public class TimeClassAdd implements ActionListener {
int counter = 0;
public void actionPerformed(ActionEvent e) {
String status_symbol[] = new String[4];
status_symbol[0] = "Unused";
status_symbol[1] = "Green";
status_symbol[2] = "Yellow";
status_symbol[3] = "Red";
if (e.getSource() == buttonAdd) {
if (counter < 3) {
counter++;
timerLabel.setText("Time left: " + status_symbol[counter]);
} else {
timerLabel.setText("Time left: " + status_symbol[counter]);
}
} else if (e.getSource() == buttonMin) {
if (counter >= 3) {
counter = 3;
timerLabel.setText("Time left: " + status_symbol[counter]);
counter--;
} else if (counter == 2) {
timerLabel.setText("Time left: " + status_symbol[counter]);
counter--;
} else if (counter == 1) {
timerLabel.setText("Time left: " + status_symbol[counter]);
}
}
}
}
}
public static void main(String args[]) {
TimerTutorial gui = new TimerTutorial();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(500, 250);
gui.setTitle("Timer Tutorial");
gui.setVisible(true);
}
}
This while (true) will put your whole application to sleep:
while (true) {
TimeClassAdd tcAdd = new TimeClassAdd();
timer = new Timer(1000, tcAdd);
timer.start();
timerLabel.setText("IT HAS BEGUN");
}
Simply don't do this in a Swing application, at least not on the main Swing event thread since it ties up the event thread, allowing no other actions to take place. Besides since you are using a Timer, there's absolutely no need for the while loop in the first place.
Edit 1
Other problems:
Your TimeClassAdd is the ActionListener used by the Timer. The getSource returned from ActionEvent object that is passed into its actionPerformed method will be the object whose event triggered the event, here the timer not a button. So you cannot retrieve which button was pressed from this ActionEvent object.
Instead you will need to retrieve that information from the getSource() returned by the ActionEvent object passed into the the "event" class's actionPerformed method.