2010-09-13 72 views
1

我試圖在Java中的GUI,使用這些方針的東西:GUI在Java中,私有類的監聽器不工作

public class GUIApp 
{ 
    DrawingPanel dp; 
    buttonPanel bp; 
    ova = Oval; 
public GUIApp() 
    { 
     JFrame win = new JFrame("Drawing App"); 
     dp = new DrawingPanel(); 
     bp = new buttonPanel(this); 

    //Settings for panels and frame 

     ova = new Oval(100,100,100,100); 

     } 
     public void setOval(int c){ 
     //Change color of oval 
     } 
    } 

然後在我的buttonPanel類我有這樣的:

public class ButtonPanel extends JPanel 
{ 

    private JButton btnRed, btnGreen, btnBlue; 

    public ButtonPanel(GUIApp d) 
    { 

     ButtonListener listener = new ButtonListener(); 
     btnRed = new JButton("Red"); 
     btnGreen = new JButton("Green"); 
     btnBlue = new JButton("Blue"); 

     btnRed.addActionListener(listener); 
     btnGreen.addActionListener(listener); 
     btnBlue.addActionListener(listener); 

     setBackground(Color.lightGray); 
     GridLayout grid = new GridLayout(3,1); 
     add(btnRed,grid); 
     add(btnGreen,grid); 
     add(btnBlue,grid); 
    } 

    private class ButtonListener implements ActionListener{ 

     public void clickButton(ActionEvent event) { 
      Object location = event.getSource(); 
      if (location == btnRed){ 
       d.setOval(1); 
      } 
      else if(location == btnGreen){ 
       d.setOval(2); 
      } 
      else if(location == btnBlue){ 
       d.setOval(3); 
     } 
     } 

} 
} 

但netbeans給內部的ButtonListener類提供了一個錯誤,我不知道爲什麼。我也不知道如何正確地從該類中調用setOval到GUIApp類。我究竟做錯了什麼?

+2

所以我們知道你得到一個錯誤......但我們不知道那個錯誤是什麼。 *總是*說錯誤是什麼 - 否則就像去看醫生,說你感覺不好,但不是以什麼方式說。請閱讀http://tinyurl.com/so-hints – 2010-09-13 06:32:35

回答

3

問題是,當您執行ActionListener時,您必須定義方法actionPerformed(ActionEvent e);你沒有在你的ButtonListener課上做到這一點。你不能用任何你想要的方法來命名你的方法(就像你用clickButton所做的那樣),所以你應該把你的clickButton方法重命名爲actionPerformed(然後繼續添加一個@Override註解)。

現在爲了在內部類中調用d.setOval,當調用actionPerformed方法時,d必須位於範圍內。有幾種方法可以實現這一點:您可以使d成爲您班級的成員變量,或者您可以將您的ButtonListener定義爲匿名班級。

例如,如果您保存d作爲成員變量,然後你的代碼應該是這樣的:

public class ButtonPanel { 
private GUIApp d; 

public ButtonPanel(GUIApp d) { 
    this.d = d; 
    // The rest of your code here... 
} 
} 

或者,你可以使用匿名類是這樣的:

public ButtonPanel(GUIApp d) { 
ActionListener listener = new ActionListener(){ 
    @Override 
    public void actionPerformed(ActionEvent event) { 
    Object location = event.getSource(); 
    if (btnRed.equals(location)) { 
    d.setOval(1); 
    } else if (btnGreen.equals(location)) { 
    d.setOval(2); 
    } else if (btnBlue.equals(location)) { 
    d.setOval(3); 
    } 
    } 
}; 
// The rest of your constructor code here ... 
} 

注:請注意我是如何將==改爲equals()用於對象相等的。

+0

此外,'d'似乎沒有在監聽器類 – Guillaume 2010-09-13 06:35:20

+0

中聲明感謝你,但我怎麼從內部調用'd.setOval(c)'內部課堂? – 2010-09-13 06:39:47

+1

'event.getSource()'返回代碼中使用的(在本例中)JButton的特定實例,所以'btnRed == location'將正常工作。 – 2010-09-13 06:47:09