Skip to content
Advertisement

Problem with Inner Class. Illegal Start of Expression error

I am practicing using inner classes but am having difficulty with a homework question: It is as follows:

Create a Swing component class BetterButtons that extends JPanel and has three Jbutton instances labelled “One”, “Two”, and “Three”. In the constructor of BetterButtons, write a local class ButtonListener that implements ActionListener. This local class has a field String name and a constructor that takes a String parameter that it assigns to the field name. The method void actionPerformed outputs on the console notification that button labeled name has been pressed. In the constructor of BetterButtons, create three instances of ButtonListener, one for each button listening to its actions.

I am almost finished, however, I get an illegal start of expression error at the line:

 public void actionPerformed(ActionEvent e){

Here is my code:

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

public class BetterButtons extends JPanel {
JButton one, two, three;
JPanel p;
public BetterButtons() {
    class ButtonListener implements ActionListener {
        String name;
        *****public ButtonListener(String name) {****
                public void actionPerformed(ActionEvent e){
                    System.out.println("Button "+name+"has been pressed.");
                }
              }
          }
    one = new JButton("One");
    two = new JButton("Two");
    three = new JButton("Three");
    one.addActionListener(new ButtonListener());
    two.addActionListener(new ButtonListener());
    three.addActionListener(new ButtonListener());
    p = new JPanel();
    p.add(one);
    p.add(two);
    p.add(three);
    this.add(p);
}
  public static void main(String[] args) {
    JFrame f = new JFrame("Lab 2 Exercise 2");
    BetterButtons w = new BetterButtons();
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f.getContentPane().setLayout(new FlowLayout());
    f.getContentPane().add(w);
    f.pack();
    f.setVisible(true);
}
}

Also, how can I reference the proper value to be assigned to the string variable name?

Thank you in advance

Advertisement

Answer

I think your definition of buttonListener should be:

class ButtonListener implements ActionListener {
    String name;
    public ButtonListener(String name) {
            this.name = name;
     }
     public void actionPerformed(ActionEvent e){
                System.out.println("Button "+name+"has been pressed.");
     }

  }

And then pass a name to each instantiation of buttonlistener, e.g.:

  one.addActionListener(new ButtonListener("one"));

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement