使用ActionListener是不好的做法(这个)

时间:2013-08-09 15:51:32

标签: java swing actionlistener

在回复我的一个答案的评论中,Hovercraft

  

不,你的建议会让事情变得更糟,因为通过使用它作为ActionListener,你建议他让他的View也成为一个控制,这不应该在除了&之外的任何事情上完成。 #34;玩具"程序

作为一个新手,我一直在使用这个'我不清楚为什么这样气馁。有人可以解释/详细说明气垫船的答案还是给另一个答案?

Comment-- https://stackoverflow.com/questions/18021509/how-can-i-call-method-with-a-string/18021674#18021674

1 个答案:

答案 0 :(得分:4)

这是因为Swing遵循MVC模式。如果您将ControllerView委托给一个班级,那就错了。另请阅读Single Responsability Principle,一个班级应该对一件事负责,如果不是,那么您的班级似乎就像God一样。

而不是

public class MyJFrame extends JFrame implements KeyListener{
     MyJFrame(){
       this.addKeyListener(this); // sounds awful           
     }
}

使用类似的东西:

public class MyFrameView {

private JFrame frame;

     MyFrameView(){
       frame = new JFrame();
       frame.addKeyListener(new MyKeyListener());
     }

}

public class MyKeyListener implements KeyListener{

}