Reputation: 21
I keep getting error that I cannot add action listener to object. I am trying to add it to my main frame in order to set it in the correct location.
public class Grid extends JPanel{
public Grid (String title){
setLayout(null);
setSize(295,295);
setLocation(10,10);
buttons = new JButton[5][5];
for(int row=0; row<5; row++) {
for(int col=0; col<5; col++) {
buttons[row][col] = new JButton();
buttons[row][col].setLocation(5+col*55, 5+row*55);
buttons[row][col].setSize(50,50);
buttons[row][col].setBackground(colours[randCol()]);
buttons[row][col].addActionListener(this);
add(buttons[row][col]);
}
}
}
}
Upvotes: 2
Views: 579
Reputation: 1694
ActionListener
is an interface and therefore you have to override all the methods. I thought that was obvious, that is why I did not explicitly point that out. Sorry for that, but you have to know that. If you have implements
, then it is always an interface and you have to implement all the methods it contains. This is one of the basic rules in Java.
Upvotes: 0
Reputation: 312
you have to implement ActionListener class
public class Grid extends JPanel implements ActionListener{
JButton[][] buttons;
public Grid (String title){
setLayout(null);
setSize(295,295);
setLocation(10,10);
buttons = new JButton[5][5];
for(int row=0; row<5; row++) {
for(int col=0; col<5; col++) {
buttons[row][col] = new JButton();
buttons[row][col].setLocation(5+col*55, 5+row*55);
buttons[row][col].setSize(50,50);
buttons[row][col].addActionListener(this);
add(buttons[row][col]);
}
}
} @Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
}
}
now its working fine
Upvotes: 0
Reputation: 1694
You have to implement the ActionListener
class in Grid class. Only then you can pass this to the addActionListener()
method.
Upvotes: 0
Reputation: 17474
i have implented the actionlistener in the grid class and i receive this, cgame.Grid is not abstract and does not override abstract method actionPerformed(java.awt.event.ActionEvent) in java.awt.event.ActionListener
That is because whenever a class implements an interface, it needs to override all available abstract methods from the interface (be it you are interested to use it or not).
Under the interface of ActionListener
, there is one abstract method
actionPerformed(ActionEvent)
If your Grid class implements ActionListener, then it shall override it as well:
class Grid extends JPanel implements ActionListener{
//your other attributes, initializations & constructors..
@Override
public void actionPerformed(ActionEvent e){
//your actions..
}
}
I would advise you to use a Layout for your Grid class. From the naming of your class Grid
. You can consider using GridLayout if you intend to arrange your components into boxes (or grids) of similar sizes. Alternatively, you may consider GridBagLayout if some of your grids has different width and/or height.
Upvotes: 4