简体   繁体   中英

Composition over Inheritance

i saw an example of ActionListener use in code by implementing ActionListener. but here i wanna use functionality of ActionListener by using Ref.Var. of ActionListener.

JButton createButton(){
    ActionListener al;       
    JButton button = new JButton();

    button.setBounds(130, 100, 100, 40); 
    button.setText("aaa");
    button.setSize(100, 40);
    button.setLayout(null);
    frame.add(button);

    return button;       
}

look at ActionListener reference here . how to use this ref.var on button to listen event on button

JButton createButton(){
    ActionListener al = new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent event) {
        // run code;
      }
    };       
    JButton button = new JButton();

    button.setBounds(130, 100, 100, 40); 
    button.setText("aaa");
    button.setSize(100, 40);
    button.addActionListener(al);
    frame.add(button);

    return button;       
}

OR

jButton.addActionListener(new ActionListener() { 
  @Override
  public void actionPerformed(ActionEvent e) { 
    //run code;
  } 
} );

It's basically exactly the same as having the containing class implement ActionListener: you provide an implementation, and you configure your button to listen to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM