Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Make Multiple jButtons do the same action.  RSS feed

 
Arshad Hosein
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys, i need some help writing a program using a Swing interface. Basically the program does specific Math questions for topics that they teach in schools where i live. The problem I'm getting is that there's a button that will reset all the jTextFields and variables used in the program and since I am continually updating the program it gets a little tedious to update every occurrence of that button throughout the entire program (there are about 8 at the moment). I tried making it a method in the same class and i tried making it its own class but those both failed. Any ideas how i could do this? or a better solution overall? Any help will be greatly appreciated. It's also worth noting that I'm new to Java but I've come quite some way in the short time I've been learning, also, this is not for any class or course, only as a hobby. Thanks Guys!
 
Stephan van Hulst
Saloon Keeper
Posts: 7808
142
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to CodeRanch, Arshad!

Simply make one ActionListener instance, and then add it to all the buttons.
 
Arun Chidam
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Arshad,
check the below link which got some useful examples on Swing Button.
Button examples
 
Ranganathan Kaliyur Mannar
Bartender
Posts: 1103
10
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the buttons have the same text/icon and same operation, you can consider creating a javax.swing.Action object and setting it to all the buttons. In case you are having one page for one question and use a Next-Previous button to navigate from one question to other (and with the Button repeating), you should consider the use of CardLayout.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!