2016-03-09 95 views
2

我不斷收到無法將動作偵聽器添加到對象的錯誤。我試圖將它添加到我的主框架,以便將其設置在正確的位置。無法在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]); 
      } 
     } 
    } 
} 
+0

我已經在網格類中實現了actionlistener,並且我收到了這個消息,cgame.Grid不是抽象的,也不會覆蓋java.awt.event.ActionListener中的抽象方法actionPerformed(java.awt.event.ActionEvent) –

+0

[How編寫一個Action Listeners](http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html) – MadProgrammer

回答

0

您必須在Grid類中實現ActionListener類。只有這樣您才能將這個轉換爲addActionListener()方法。

4

我已經implented在網格類的ActionListener和我收到此,cgame.Grid不是抽象的,不覆蓋java.awt.event.ActionListener抽象方法的actionPerformed(java.awt.event.ActionEvent中)

這是因爲當一個類實現一個接口,它需要覆蓋從界面所有可用的抽象方法(可能是你有興趣使用或不使用)。

ActionListener界面,有一個抽象方法

actionPerformed(ActionEvent) 

如果您電網類實現的ActionListener,那麼它應重寫它還有:

class Grid extends JPanel implements ActionListener{ 

    //your other attributes, initializations & constructors.. 

    @Override 
    public void actionPerformed(ActionEvent e){ 
     //your actions.. 
    } 
} 

我會建議你使用佈局f或你的網格類。從你的班級Grid的命名。您可以考慮使用網格佈局如果你打算將組件安排成箱(或網格)類似的尺寸。或者,如果某些網格具有不同的寬度和/或高度,則可以考慮使用GridBagLayout

+0

int nummoves = 0;對於(int row = 0; row <5; row ++){ for(int col = 0; col <5; col ++){if(a.getSource()== buttons){public void actionPerformed(ActionEvent a){ column.setText(「COL:」+(col + 1)); [row] [col]){ rows.setText(「ROW:」+(row + 1)); nummoves ++; 移動。setText(「Moves:」+ nummoves); } } } } –

+1

@SamKadish你是什麼意思的這些代碼?點擊編輯按鈕,您可以隨時在當前問題中添加其他代碼。 – user3437460

0

你必須實現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 

    } 
} 

現在它工作正常

0

ActionListener是一個接口,因此,你必須覆蓋所有方法。我認爲這很明顯,這就是爲什麼我沒有明確指出這一點。對不起,但你必須知道這一點。如果你有implements,那麼它總是一個接口,你必須實現它包含的所有方法。這是Java中的基本規則之一。

相關問題