Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

actionListener help

hello!! I am making a battleships game at the moment but am having a bit of trouble. I have made two button arrays that i have displayed in a grid formation, one of the grids is yellow. This is all fine but i would now like to add an actionListener to it that, once a button is clicked, it changes the color of the button!!

here is samples of my code to help you understand:

JButton[][] enemyButtons = new JButton[10][10];
for (int i = 0; i < enemyButtons.length; i++)
{
for (int j = 0; j < enemyButtons[i].length; j++)
{

enemyButtons[i][j] = new JButton();
enemyButtons[i][j].setPreferredSize(gridButtonSize);
//enemyButtons[i][j].addActionListener(new myEvent());
enemyButtons[i][j].setBackground(Color.yellow);

grid2.add(enemyButtons[i][j]);
}
}
This is my button array, as you can see it is multi-dimentional and to make a 10x10 grid each button is given an incremental number of enemyButtons[i][j], i am having trouble trying to get this code to work:

/*class myEvent extends actionListener
{
public void actionPerformed1(ActionEvent ae)
{
Object obj = ae.getSource();
JButton clickedButton = (JButton)obj;
clickedButton.setBackground(Color.red);
}
}*/

One problem is that i already have an action listener that makes an Exit button close down the frame, are the two action commands getting on top of each other??

can you help me please?

i think i might need to use an inner class, but have read tutorials and niether an inner or annoymous class will work??

thank you
[1722 byte] By [zoidberg] at [2007-11-11 7:26:41]
# 1 Re: actionListener help
you can't call the method actionPerformed1() as it will never be called. (unless you call it yourself) And your class "myEvent" is trying to extend an interface that doesn't even exist. It is case-sensitive, so it should be ActionListener and you should "implement" the interface, not extend.

Make a seperate listener class for just only the battleship buttons. This would be your inner class which goes inside the main class which creates the buttons. Then add this to each button you create:
//only need 1 instance of the listener class.
GridButtonListener gridButtonListener = new GridButtonListener();

//for(int i=0;.........
enemyButtons[i][j].addActionListener(gridButtonListener);

class GridButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//make sure source of event is from a JButton object
if (e.getSource() instanceof JButton)
{
//cast source to a JButton and change background color
((JButton)e.getSource()).setBackground(Color.red);
}
}
}
Phaelax at 2007-11-11 22:38:20 >