2016-12-16 108 views
1

我試圖讓我的第二個按鈕減去起始數字,但我不斷收到錯誤,其中ButtonListener1位於(行23和47),我無法運行我的代碼。
我不明白爲什麼它不起作用。
請聯繫我,如果我應該添加一些東西到按鈕和操作在私人課程或主類。爲什麼我的第二個按鈕不起作用?

package addsubtract; 

import javax.swing.JApplet; 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class SubtractAdd extends JApplet { 

    private int APPLET_WIDTH = 300, APPLET_HEIGHT = 35; 
    private int num; 
    private JLabel label; 
    private JButton add; 
    private JButton subtract; 

    public void init() 
    { 
     num = 50; 

     add = new JButton ("Add"); 
     add.addActionListener (new ButtonListener()); 
     subtract = new JButton ("Subtract"); 
     subtract.addActionListener ((ActionListener) new ButtonListener1()); 

     label = new JLabel("Number: " + Integer.toString (num)); 

     Container cp = getContentPane(); 
     cp.setBackground (Color.PINK); 
     cp.setLayout (new FlowLayout()); 
     cp.add(add); 
     cp.add(subtract); 
     cp.add(label); 

     setSize (APPLET_WIDTH, APPLET_HEIGHT); 

    } 

    private class ButtonListener implements ActionListener 
    { 
     public void actionPerformed (ActionEvent event) 
     { 
      num++; 
      label.setText("Number: " + Integer.toString(num)); 

     } 

    private class ButtonListener1 implements ActionListener 
    { 
     public void actionPerfomred (ActionEvent event)  
     { 
      num--; 
      label.setText("Number: " + Integer.toString(num)); 

     } 
    } 
    } 
} 
+0

什麼是你得到 – Jobin

+0

'但錯誤我不斷收到錯誤'什麼錯誤是什麼,在哪一行? – user3437460

+0

我們不能幫助您,直到您發佈您的錯誤,它們發生在哪裏 –

回答

3

我不認爲你需要私人課程。此外,我相信他們正在引起您的範圍問題(不能從其中訪問num)。

相反,你可以做匿名類

add = new JButton ("Add"); 
add.addActionListener (new ActionListener() { 
    @Override 
    public void actionPerformed (ActionEvent event) { 
     label.setText("Number: " + (++num)); 
    } 
}); 
subtract = new JButton ("Subtract"); 
subtract.addActionListener (new ActionListener() { 
    @Override 
    public void actionPerformed (ActionEvent event) { 
     label.setText("Number: " + (--num)); 
    } 
}); 

還是有類實現接口

public class SubtractAdd extends JApplet implements ActionListener { 

    public void init() { 

     add = new JButton ("Add"); 
     add.addActionListener (this); 
     subtract = new JButton ("Subtract"); 
     subtract.addActionListener(this); 

    } 

    @Override 
    public void actionPerformed (ActionEvent event) { 
     Object source = event.getSource(); 
     if (source == add) { 
      label.setText("Number: " + (++num)); 
     } else if (source == subtract) { 
      label.setText("Number: " + (--num)); 
     } 
    }); 
+0

非常感謝!如果你不介意,你可以解釋一下爲什麼要放置覆蓋功能?我只是想盡可能地理解這一點。 – Philana

+1

這不是必要的,但它有助於告訴編譯器,「嘿,這是執行不同於默認行爲」。如果你讓IDE自動完成東西,通常會添加 –

+0

好的,非常感謝你! – Philana

相關問題