How to interchange between 2 timers? in Java GUI - java

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.

Related

Getting value from JRadioButton

I'd like to change value of my variable "name" when I select right button and click "ok" on my JRadio Frame.
For example when i select r1 and hit "ok" I'd like to have name=="Fast" in the entire package.
package Snake;
public class Radio extends JFrame {
private int delay = 100;
private String name;
JTextField t1;
JButton b;
JRadioButton r1, r2;
JLabel l;
public void selectSpeed() {
b = new JButton("Ok");
r1 = new JRadioButton("Fast");
r2 = new JRadioButton("Slow");
l = new JLabel("Speed: ");
ButtonGroup bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
add(b);
add(r1);
add(r2);
add(l);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (r1.isSelected()) {
name = "Fast";
} else {
name = "Slow";
}
l.setText("Speed: " + name); // name=="Fast" when r1 is selected
} // name=="Slow" when r2 is selected
});
if (name == "Fast") { // and now name is empty...
delay = 50;
}
if (name == "Slow") {
delay = 500;
}
setLayout(new FlowLayout());
setSize(400, 400);
setVisible(true);
}
public int setSpeed() {
selectSpeed();
return delay;
}
}
If you want to change the delay on button click, You need to write the logic in the ActionListener itself because the code you have written to change the delay will run only once and that too at the start of the execution of your program and at that time, name will be empty.
Then when ever you click the button, It will only execute the ActionListener So delay will not be changed at any time. And other mistake you are making is that you are comparing Strings in wrong way. For more information take a look at it How do I compare Strings in Java?
To change delay dynamically on button click, you need to change it in the ActionListener.
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (r1.isSelected()) {
name = "Fast";
delay = 50;
} else {
name = "Slow";
delay = 500;
}
l.setText("Speed: " + name); // name=="Fast" when r1 is selected
} // name=="Slow" when r2 is selected
});
You need to do it in your JRadioButton listener. For example, like here, at first you change the variable "name" and later in the current listener you check conditions, but you need remember that to compare the strings you need to use "equals":
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (r1.isSelected()) {
name = "Fast";
} else {
name = "Slow";
}
l.setText("Speed: " + name); // name=="Fast" when r1 is selected
if (name.equals("Fast")) { // and now name is empty...
delay = 50;
}
if (name.equals("Slow")) {
delay = 500;
}
} // name=="Slow" when r2 is selected
});
Well I see my mistake now, Thank you.
But it still does not work the way I like. I'd like to change the "delay" value every time I select right button on JRadio and hit "ok" and with this changed value I'd like to go to the other class.
There is the code of a class where I need value of "delay":
package Snake;
public class Gameplay extends Paint implements KeyListener, ActionListener {
private Timer timer;
private int q = 0;
Radio radio = new Radio();
public Gameplay() {
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(radio.selectSpeed(), this); //here i need flexible "delay" value
timer.start();
}

Java Timers and actionlisteners

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

JLabel.setText() is only setting text for last element in a loop

First of all, apologies for how long winded this is.
I'm trying to make a simple roulette game that allows a user to add players, place bets for these players, and spin the roulette wheel, which is represented as a simple JLabel that updates it's text with each number it passes.
However, I've run into a bug that I'm having a lot of trouble with: the JLabel only updates the text for the last element in my loop.
Basically, my solution works like this:
When a user presses a button labelled "Spin" (given that users have been added to the game), I call a method from a class called SpinWheelService, which is an Observable singleton which in turn calls the notifyObservers() method:
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String description = null;
if (ADD_PLAYER.equals(cmd)) {
addDialog();
} else if (PLACE_BET.equals(cmd)) {
betDialog();
} else if (SPIN.equals(cmd)) {
SpinWheelService.sws.setSpinWheelService();
} else if (DISPLAY.equals(cmd)) {
System.out.println("Display selected!");
}
}
Here is my SpinWheelService class:
package model;
import java.util.*;
public class SpinWheelService extends Observable {
public static SpinWheelService sws = new SpinWheelService();
public void setSpinWheelService() {
setChanged();
notifyObservers();
}
}
The only listener registered for SpinWheelService is this class, where GameEngine is my game engine that handles internal game logic, WheelCallbackImpl is a class that updates the View:
class SpinWheelObserver implements Observer {
GameEngine gameEngine;
ArrayList<SimplePlayer> players;
WheelCallbackImpl wheelCall;
int n;
public SpinWheelObserver(GameEngine engine, WheelCallbackImpl wheel, ArrayList<SimplePlayer> playerList) {
players = playerList;
gameEngine = engine;
wheelCall = wheel;
}
public void update(Observable sender, Object arg) {
// check if any players are present
if (players.size() == 0) {
System.out.println("Empty player array!");
return;
}
do {
gameEngine.spin(40, 1, 300, 30, wheelCall);
n = wheelCall.playback();
} while (n== 0);
}
}
The main point of note here is my gameEngine.spin() method, which is this:
public class GameEngineImpl implements GameEngine {
private List<Player> playerList = new ArrayList<Player>();
// method handles the slowing down of the roulette wheel, printing numbers at an incremental delay
public void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
System.out.println("Sleep method failed.");
}
}
public void spin(int wheelSize, int initialDelay, int finalDelay,
int delayIncrement, WheelCallback callback) {
Random rand = new Random();
int curNo = rand.nextInt(wheelSize) + 1;
int finalNo = 0;
assert (curNo >= 1);
// while loop handles how long the wheel will spin for
while (initialDelay <= finalDelay) {
delay(initialDelay);
initialDelay += delayIncrement;
// handles rotating nature of the wheel, ensures that if it reaches wheel size, reverts to 1
if (curNo > wheelSize) {
curNo = 1;
callback.nextNumber(curNo, this);
curNo++;
}
assert (curNo <= wheelSize);
callback.nextNumber(curNo, this);
curNo++;
finalNo = curNo - 1;
}
calculateResult(finalNo);
callback.result(finalNo, this);
}
The method callback.nextNumber(curNo, this):
public void nextNumber(int nextNumber, GameEngine engine) {
String strNo = Integer.toString(nextNumber);
assert (nextNumber >= 1);
System.out.println(nextNumber);
wcWheel.setCounter(strNo);
}
Where in, wcWheel is my singleton instance of my View, which contains the method setCounter():
public void setCounter(String value) {
label.setText(value);
}
Sorry for how convoluted my explanation is, but basically what it boils down to is that setCounter() is definitely being called, but seems to only call the setText() method on the final number. So what I'm left with is an empty label that doesn't present the number until the entire roulette has finished spinning.
I've determined that setCounter() runs on the event dispatch thread, and I suspect this is a concurrency issue but I have no idea how to correct it.
I've tried to include all relevant code, but if I'm missing anything, please mention it and I'll post it up as well.
I'm at my wits end here, so if anyone would be kind of enough to help, that would be so great.
Thank you!
Your while loop along Thread.sleep() will block and repainting or changing of the UI until the loop is finished.
Instead you'll want to implement a javax.swing.Timer for the delay, and keep a counter for the number of ticks, to stop it. You can see more at How to Use Swing Timers
The basic construct is
Timer ( int delayInMillis, ActionListener listener )
where delayInMillis is the millisecond delay between firing of an ActionEvent. This event is listened for by the listener. So every time the event is fired, the actionPerfomed of the listener is called. So you might do something like this:
Timer timer = new Timer(delay, new ActionListener()(
#Override
public void actionPerformed(ActionEvent e) {
if (count == 0) {
((Timer)e.getSource()).stop();
} else {
//make a change to your label
count--;
}
}
));
You can call timer.start() to start the timer. Every delay milliseconds, the label will change to what you need it to, until some arbitrary count reaches 0, then timer stops. You can then set the count variable to whatever you need to, if you want to to be random, say depending on how hard the wheel is spun :D
I think you didn't post all the relevant code that is required to know exactly the problem.
But most likely the problem is due to you run your loop and JLabel.setText() in the EDT (Event Dispatching Thread).
Note that updating the UI components (e.g. the text of a JLabel) also happens in the EDT, so while your loop runs in the EDT, the text will not be updated, only after your loop ended and you return from your event listener. Then since you modified the text of the JLabel it will be refreshed / repainted and you will see the last value you set to it.
Example to demonstrate this. In the following example a loop in the event listener loops from 0 to 9 and sets the text of the label, but you will only see the final 9 be set:
JPanel p = new JPanel();
final JLabel l = new JLabel("-1");
p.add(l);
JButton b = new JButton("Loop");
p.add(b);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for ( int i = 0; i < 10; i++ ) {
l.setText( "" + i );
try { Thread.sleep( 200 ); } catch ( InterruptedException e1 ) {}
}
}
} );
A proposed solution: Use javax.swing.Timer to do the loop's work. Swing's timer calls its listeners in the EDT so it's safe to update swing components in it, and once the listener returns, a component UI update can happen immediately:
JPanel p = new JPanel();
final JLabel l = new JLabel("-1");
p.add(l);
JButton b = new JButton("Loop");
p.add(b);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new Timer(200, new ActionListener() {
int i = 0;
#Override
public void actionPerformed(ActionEvent e2) {
l.setText("" + i);
if ( ++i == 10 )
((Timer)e2.getSource()).stop();
}
}).start();
}
} );
In this solution you will see the label's text counting from 0 up to 9 nicely.
It's appears to me that your entire game must block in the action handler until the while loop has finished? So the text of the label will be getting updated but only the last update will be visible once the AWT thread is running again.

Displaying correct information in JPanel

I'm having trouble updating JPanels with new data. I'm working on a game, the basic concept of what I'm trying to do is load a player and display the items he holds in a JPanel (set out in a box layout) I am using a thread and loop to update the player items. This works fine for one player but my game allows for additional players which the user can switch between. When I switch to the next player I want their details to be loaded and updated. This doesn't work.
This is just a snippet of the code but I'm hoping someone will be able to see my problem.
private JFrame frame;
private JPanel mainPanel;
private Box Item1 Item2, Item3;
static private JPanel centerPanel;
private boolean playerLoaded;
private Player currentPlayer;
private Thread gameThread;
public void run(){
while (running){
for (Player player:allPlayers){
playerLoaded = false;
currentPlayer = player;
player.setCurrentTurn(true);
while (player.isCurrentTurn()){
if (playerLoaded != true){
loadPlayer(player);
loadItems(player);
playerLoaded = true;
}
if ((playerLoaded == true){
updateItems(player);
try {
Thread.sleep(999);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
public void loadPlayer(Player player){
jlCurrentPlayer.setText("Player: " + player.getName());
}
public void loadItems(Player player){
int count = 1;
centerPanel = new JPanel(new GridLayout(1,3));
for (Item Item : player.getAllItems()){
if (count == 1) {
Item1 = Box.createVerticalBox();
Item1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
JLabel jlItem = new JLabel(item.getName());
Item1.add(jlItem);
centerPanel.add(Item1);
}
else if (count ==2){
Item2 = Box.createVerticalBox();
Item2.setBorder(BorderFactory.createLineBorder(Color.BLACK));
JLabel jlItem = new JLabel(item.getName());
Item2.add(jlItem);
centerPanel.add(Item2);
}
else if (count ==3){
Item3 = Box.createVerticalBox();
Item3.setBorder(BorderFactory.createLineBorder(Color.BLACK));
JLabel jlItem = new JLabel(item.getName());
Item3.add(jlItem);
centerPanel.add(Item3);
}
mainPanel.add(centerPanel,BorderLayout.CENTER);
count++;
}
}
public void updateItemstats(Player player){
int count = 1;
if (player.isCurrentTurn()){
for (Item item : player.getAllItems()){
if ((count == 1) && (player.isCurrentTurn())) {
Item1.add(Box.createVerticalGlue());
Item1.add(new JLabel("Value: " + item.getstats().getValue()));
Item1.add(new JLabel("Quality: " + item.getStats().getQuality()));
}
else if (count ==2){
Item2.add(Box.createVerticalGlue());
Item2.add(new JLabel("Value: " + item.getstats().getValue()));
Item2.add(new JLabel("Quality: " + item.getStats().getQuality()));
}
else if (count ==3){
Item3.add(Box.createVerticalGlue());
Item3.add(new JLabel("Value: " + item.getstats().getValue()));
Item3.add(new JLabel("Quality: " + item.getStats().getQuality()));
}
count++;
}
}
}
JButton jbNext = new JButton("Next Player");
jbNext.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
currentPlayer.setCurrentTurn(false);
}
});
For my main frame I am using a Border Layout. Whats happening when I switch players is basically the updated information is sometimes a mix of player 1 and 2. e.g.
value 25
Quality 60
value 50
Quality 20.
In addition if player 1 has 1 Item and player 2 has 3 Items and I switch from player 2 to 1 sometimes player 1 will have all of player 2 items instead of his own.
I thought it might be an issue with the Item1 2 and 3 panels so I tried to remove them on next player btn click but this just caused an exception. This may well be the problem still and I may not be removing them correctly.
Can anyone out there help me out with this?
You should call setCurrentTurn(true) for the next Player in the next player action Listener.
Have you set the currentPlayer variable in Player to volatile? Important: Both the private Player currentPlayer and the private boolean currentPlayer in the Player.java must be volatile. (Have a look at http://javamex.com/tutorials/synchronization_volatile.shtml)
Also, use a Monitor and wait() instead of Thread.sleep that way you can use notify() to wake up the waiting Thread.
Here are some suggestions for your code, but be aware that you will have to do more (e.G. in the Player.java class that you did not show).
volatile List<Player> players = ...; // load your list of Player
volatile int currentPlayerIndex = 0;
volatile Player currentPlayer = null;
private final Object WAIT_MONITOR = new Object(); // yes, 'new Object()' !
[...]
public void run() throws InterruptedException {
playerLoop:
while(programRunning) { // maybe while(true)
synchronized (WAIT_MONITOR) {
loadPlayer(currentPlayer);
loadItems(currentPlayer);
updateItems(currentPlayer);
WAIT_MONITOR.wait(1000);
}
}
}
[...]
JButton jbNext = new JButton("Next Player");
jbNext.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
synchronized(WAIT_MONITOR) { // this causes that the contents of run() and this method do not run at the same time.
currentPlayer.setCurrentTurn(false);
if(players.size() > currentPlayerIndex + 1) // don't use >=
currentPlayerIndex++;
else
currentPlayerIndex = 0; // reset at the end of the list
currentPlayer = players.get(currentPlayerIndex);
currentPlayer.setCurrentTurn(true);
WAIT_MONITOR.notifyAll(); // that causes the wait() method above to be continued.
}
}
});

How to implement actionlistener inside a Timer program?

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.

Categories

Resources