1

您好,我有这个类实现了一个 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 类吗?:)

4

1 回答 1

2

我想这已经足够了:

ExpressionView.instance.addActionListener(ExpressionListener.instance);

既然它们都是单例类,为什么你需要一个静态addActionListenerExpressionView?您已经可以从JTextFieldon ExpressionViewsingleton 实例继承一个。

于 2013-01-13T17:41:04.543 回答