*
The moose likes Swing / AWT / SWT and the fly likes Array of 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 "Array of JButtons" Watch "Array of JButtons" New topic
Author

Array of JButtons

Rocky Summers
Ranch Hand

Joined: Nov 07, 2003
Posts: 66
Hi Fellas..
I'm having lots of problems with my array of jbuttons... i dont know how to do the button's addActionListener... here's how my code looks like:

So now, when i click on the buttons... it gives me a null pointer exception.. i know why that happens: it's because i=5.. right? but i have no idea how to associate message.get(4) with button[4]... or message.get(2) with button[2]... and i dont want to hardcode all this in cuz the values are gonna be dynamic..
any way i can get around this prob? your help is very much appreciated..
thank you.
rocky
Craig Wood
Ranch Hand

Joined: Jan 14, 2004
Posts: 1535
You generally have two options:
1 - name each button and put the names in the button_subject array; here you can test for each button in actionPerformed with if(button == namedButton),
2 - set an action command for each button in the array as shown below; here you can test for the button with if(ac.equals("id1")).
One benefit of the second approach is that your code will not break when internationalized, the text on the button will be changed but the action command string will be unchanged.

You could of course add an individual ActionListener to each button as you were doing, there's nothing wrong with doing it that way.
Rocky Summers
Ranch Hand

Joined: Nov 07, 2003
Posts: 66
hi craig!
thanks for the answer! i tried doing the exact same thing.. but one thing bothers me though.. what if one of the names of the buttons have the exact same text.. cuz what i'm doing here, is i'm grabbing stuff from the database and putting them in buttons so when i click on that button, i can open up a small popup on that field's corresponding info..
Craig Wood
Ranch Hand

Joined: Jan 14, 2004
Posts: 1535
Then adding an action listener to each button makes more sense.
Nathan Pruett
Bartender

Joined: Oct 18, 2000
Posts: 4121

The above option is probably the best for this case, but I would also like to point out that you could still do the one big listener option even if buttons had the same text. The actionCommand of the button is by default the same as the text, but you can set it to anything you want. This is the value you can use in your listener to differentiate between multiple buttons with the same displayed text.


-Nate
Write once, run anywhere, because there's nowhere to hide! - /. A.C.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Array of JButtons
 
Similar Threads
Creating and opening a window if the button is clicked in an applet
GridBag help
JPanels with different content should have the same size
Dialog resize problem
GridBag gremlins!