【问题标题】:what does "must implement the inherited abstract method java.awt.event.ActionListener.actionPerformed(java.awt.event.ActionEvent)" mean?“必须实现继承的抽象方法 java.awt.event.ActionListener.actionPerformed(java.awt.event.ActionEvent)”是什么意思?
【发布时间】:2017-01-30 14:26:27
【问题描述】:

我在代码中遇到了障碍。这是手头的课程。

public class StartRoom extends Room implements ActionListener {

   JButton buttonTwo;

   public StartRoom() {
      start();
      buttonOne = new JButton("Go to door.");
      buttonTwo = new JButton("Look at skeleton.");
      label = new JLabel("You walk into the dungeon, the room is covered with vines. There is a skeleton sitting near the northern door. What do you do?");
      panelOne.add(label);
      panelOne.add(buttonOne);
      buttonOne.addActionListener(this); 
      buttonTwo.addActionListener(this);
   }

   class MyActionListener implements ActionListener {
      @Override
      public void actionPerformed(java.awt.event.ActionEvent ae) {

      } 
   }

   public static void main( String[]args ) {
      new StartRoom();
   }
}

它说StartRoom类型必须在第五行实现继承的抽象方法java.awt.event.ActionListener.actionPerformed(java.awt.event.ActionEvent),但我不知道它在问什么!

【问题讨论】:

  • 必须继承ActionListener的抽象方法actionPerformed(ActionEvent)。如果您阅读错误,我认为这很明显。如果你不理解这里的一个术语,那么你可能没有完全理解 OO。所以再读一遍
  • 为什么会有这么多赞?提问者显然忘记了实现他们的接口。也许是朋友的支持?或者我只是迷信/偏执。

标签: java drjava


【解决方案1】:

StartRoom implements ActionListener 表示StartRoom 应该承担ActionListener 的合约。方法actionPerformed( ActionEvent)必须自己实现。

public class StartRoom extends Room implements ActionListener {
   ...

   @Override
   public void actionPerformed(java.awt.event.ActionEvent ae) {
      // your code here....
   } 
}

如果您想委托给另一个类,例如MyActionListener,您必须更改buttonTwo.addActionListener(this); 中的用法,将this 替换为MyActionListener 的实例。

MyActionListener toto = new MyActionListener();
buttonTwo.addActionListener( toto );

在后一种情况下,您应该从 StartRoom 类声明中删除 implements ActionListener

【讨论】:

    【解决方案2】:

    当你实现某个东西时,你将该类用作接口,这意味着你必须使用并重新定义你正在实现的类中的每个方法。但是,如果您想按原样使用该类的方法,那么您可以扩展它并使该类成为您的类的超类。请记住,您只能扩展一个类,但您可以将大量类实现为接口。

    【讨论】:

      猜你喜欢
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多