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... or message.get(2) with button... 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
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.
Joined: Nov 07, 2003
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..
Joined: Jan 14, 2004
Then adding an action listener to each button makes more sense.
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.
Write once, run anywhere, because there's nowhere to hide! - /. A.C.