John Kebab
John Kebab

Reputation: 25

How to add an ActionListener to this class implementing JTextField

Hi there I have this class implementing a JTextField:

Which also should have an addActoinListener method, which I am not sure how to write...

package gui;

import gui.control.ExpressionListener;
import gui.control.NewListener;

import javax.swing.JTextField;

public final class ExpressionView
    extends JTextField {

public String text;

public static final long serialVersionUID = 1L;

public static final ExpressionView instance = new ExpressionView();

private ExpressionView() {
    super("ExpressionView");

    // This is a singleton.
}

@Override
private void addActionListener {
    ExpressionView.addActionListener(ExpressionListener.instance);
}


}

The ExpressionListener class which kind of performs the action looks like this:

package gui.control;

import gui.ExpressionView;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Scanner;

import spreadsheet.Application;
import spreadsheet.Expression;
import spreadsheet.exception.NoSuchSpreadsheetException;
import ui.ExpressionInterpreter;
import ui.exception.IllegalStartOfExpression;
import ui.exception.InvalidExpression;
import ui.exception.InvalidPositionException;

public final class ExpressionListener
    implements ActionListener {

  public static final ExpressionListener instance = new ExpressionListener();

  private ExpressionListener() {
    // This is a singleton.
  }
  @Override
  public void actionPerformed(ActionEvent event) {
    try {
      Scanner scanner = new Scanner(ExpressionView.instance.getText());
      Expression expression = ExpressionInterpreter.interpret(scanner);
      Application.instance.set(expression);
    } catch (InvalidPositionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchSpreadsheetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStartOfExpression e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidExpression e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


  }

}

So could you please help me and show me how to add this ActionListener to the ExpressionView class? :)

Upvotes: 1

Views: 469

Answers (1)

Jack
Jack

Reputation: 133567

I guess this is enough:

ExpressionView.instance.addActionListener(ExpressionListener.instance);

Since they are both singleton classes why would you need a static addActionListener to ExpressionView class? You can already the one inherited from the JTextField on ExpressionView singleton instance.

Upvotes: 2

Related Questions