2016-12-16 51 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

相关问题