我试图让我的第二个按钮减去起始编号,但我一直收到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 :(得分: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));
}
});