This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes jbuttons Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "jbuttons" Watch "jbuttons" New topic
Author

jbuttons

maya jain
Greenhorn

Joined: Feb 22, 2011
Posts: 5
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

Joined: Jun 13, 2009
Posts: 2373
    
    8
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

Joined: Oct 13, 2005
Posts: 43957
    
  33
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

Joined: May 03, 2008
Posts: 4990
    
    8

Maya, please BeForthrightWhenCrossPostingToOtherSites
http://www.java-forums.org/awt-swing/40626-jbuttons.html


luck, db
There are no new questions, but there may be new answers.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 20078
    
  30

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
maya jain
Greenhorn

Joined: Feb 22, 2011
Posts: 5
Thanks for the help
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 20078
    
  30

You're welcome.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: jbuttons
 
It's not a secret anymore!