This week's book giveaway is in the Java in General forum.
We're giving away four copies of Think Java: How to Think Like a Computer Scientist and have Allen B. Downey & Chris Mayfield on-line!
See this thread for details.
Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

jbuttons

 
maya jain
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am trying to implement an action listener for an array of Jbutton without name. I want the first button to display A, second to display B.... I know that this code displays A which ever button I press. I am unable to come up with any idea please help me.


Thanks.
 
Rob Camick
Ranch Hand
Posts: 2580
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know that this code displays A which ever button I press


Well thats what you are telling your code to do:



If you always set the value of i to 0, thats what happens. The question is why are you doing this?

You went to all the trouble to set the action command when you created the button:



So why don't you use the getActionCommand() method of JButton the get the proper value?
 
Campbell Ritchie
Sheriff
Posts: 48921
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did you put that bit about int i = 0; in order to persuade the code to compile? Did you have compiler errors about "must be declared final"? That is because you are trying to go about it in a non-OO fashion. If you followed Rob Camick's suggestion, you would have a field of the button which represents your letter, and you would use that field. There are several alternative fields you might use instead.
 
Darryl Burke
Bartender
Posts: 5126
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maya, please BeForthrightWhenCrossPostingToOtherSites
http://www.java-forums.org/awt-swing/40626-jbuttons.html
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see two options:
1) use another final variable within the loop, just to hold the current value of i. Meh.

2) use a specific class. Let's make it method local:
Class CharActionListener is only available within this method.
 
maya jain
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the help
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic