[英]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.