嗨,我有实现JTextField的此类:

哪个也应该有一个addActoinListener方法,我不确定该怎么写...

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);
}


}


这种执行动作的ExpressionListener类如下所示:

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();
    }


  }

}


所以,请您帮我一下,向我展示如何将此ActionListener添加到ExpressionView类中? :)

最佳答案

我想这足够了:

ExpressionView.instance.addActionListener(ExpressionListener.instance);


由于它们都是单例类,为什么您需要一个静态的addActionListenerExpressionView类?您已经可以从JTextField单例实例的ExpressionView继承一个。

10-05 22:02