分享

addActionListener(this)

 好汉勃士 2021-12-18

addActionListener(this)

看书的时候看到这行代码,觉得很奇怪

不是一般写成

  1. button.addActionListener(new ActionListener() {
  2. public void actionPerformed(ActionEvent e) {
  3. ...
  4. name.setText(selectedName);
  5. }
  6. });

 要一个ActionListener对象,结果一看

  1. public class YourClass implements ActionListener {
  2. ... // Other code for your class
  3. public void actionPerformed(ActionEvent actionEvent) {
  4. System.out.println('I was selected.');
  5. }
  6. // Code within some method
  7. JButton button = new JButton(...);
  8. button.addActionListener(this);
  9. // More code within some method
  10. }

 自己的类都实现了ActionListener,当然就可以addActionListener(this)

不过在YourClass里面如果有很多Button的话,你就得在actionPerformed方法里实现区分它们的方法。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约