The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

Add button listeners to 4 buttons?

Hello! My name is Joel and is kinda new to java programming. I got a problem. I want to make 4 buttons on a Panel that has 4 different timers. When i press the first one i want it to take 5 minutes and then pop up a screen with a text like this "Your eggs are ready". And i want different timers on all of the buttons. I did succed with one button but cant figure out how i can add listeners to any more buttons. And how do i add delay in a while loop?

Re: Add button listeners to 4 buttons?

Edit: Just noticed the topic is a duplicate of this one. Please don't post duplicate topics.

I've showed you how to use the same ActionListener for multiple buttons in the code below, but there are problems with this code I think you should fix:

1. A Swing application should not be run on the same thread that runs the main() method. You can find out more about proper Swing programming here.

2. An entire Swing GUI should not be run from the main() method. You may have created this runnable example in a hurry and chose the design for simplicity, but the design shown in the code you posted should not be your typical Swing application design. The main() method should be one or two lines long with the bulk of the code in the primary Swing class, often creating a JFrame, starting with its constructor.

3. Your next question might be about programming your "timers" to keep track of the actual time you had in mind. For that you'll want to learn about the javax.swing.Timer class.

4. You might also wonder about having multiple timers running at the same time. I haven't worked out that answer completely. Multiple Timer instances might be sufficient or, if not, then a SwingWorker for each button (or button press) might be appropriate. Let me know if you'd like to work on that.