[英]Unable to add action listener in JPanel
我不断收到无法将操作侦听器添加到对象的错误。 我试图将其添加到我的主框架中,以便将其设置在正确的位置。
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]);
}
}
}
}
我在网格类中强加了actionlistener,并且收到了这个消息,cgame.Grid不是抽象的,并且不会覆盖java.awt.event.ActionListener中的抽象方法actionPerformed(java.awt.event.ActionEvent)
这是因为每当一个类实现一个接口时,它都需要重写该接口中所有可用的抽象方法(无论您是否愿意使用它)。
在ActionListener
接口下,有一种抽象方法
actionPerformed(ActionEvent)
如果您的Grid类实现了ActionListener ,那么它也将覆盖它:
class Grid extends JPanel implements ActionListener{
//your other attributes, initializations & constructors..
@Override
public void actionPerformed(ActionEvent e){
//your actions..
}
}
我建议您将Layout用于Grid类。 从类Grid
的命名开始。 如果打算将组件安排到类似大小的盒子(或网格)中,则可以考虑使用GridLayout 。 或者,如果您的某些网格具有不同的宽度和/或高度,则可以考虑GridBagLayout 。
您必须在Grid类中实现ActionListener
类。 只有这样,你可以把它传递给addActionListener()
方法。
您必须实现ActionListener类
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
}
}
现在工作正常
ActionListener
是一个接口,因此您必须重写所有方法。 我认为这很明显,这就是为什么我没有明确指出。 抱歉,但是您必须知道这一点。 如果您拥有implements
,那么它始终是一个接口,您必须实现它包含的所有方法。 这是Java中的基本规则之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.