Reputation: 25
I'm trying to get my second button to subtract the starting number, but I keep getting errors where ButtonListener1 is located (line 23 and 47) and I am unable to run my code.
I don't understand why it isn't working.
Please tel me if I'm supposed to add something to the button and operation in the private classes or the main class.
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));
}
}
}
}
Upvotes: 1
Views: 67
Reputation: 191728
I don't think you need the private classes. Plus, I believe they are causing you scoping issues (can't access num
from within them).
Instead, you can make anonymous classes
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));
}
});
Or have the class implement the interface
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));
}
});
Upvotes: 3