我不断收到错误消息,无法将操作监听器添加到对象。我正在尝试将其添加到我的主框架中,以便将其设置在正确的位置。
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]);
}
}
}
}
最佳答案
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
这是因为每当一个类实现一个接口(interface)时,它都需要覆盖接口(interface)中所有可用的抽象方法(无论您是否有兴趣使用它) .
在ActionListener
接口(interface)下,有一个抽象方法
actionPerformed(ActionEvent)
如果您的Grid类实现了ActionListener,那么它也将覆盖它:
class Grid extends JPanel implements ActionListener{
//your other attributes, initializations & constructors..
@Override
public void actionPerformed(ActionEvent e){
//your actions..
}
}
我建议您为 Grid 类使用布局。从您的类 Grid
的命名开始。如果您打算将组件排列到大小相似的框(或网格)中,则可以考虑使用GridLayout。或者,如果某些网格具有不同的宽度和/或高度,您可以考虑 GridBagLayout。
关于java - 无法在 JPanel 中添加操作监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35883665/