Passing a block to a method in Java

I have a GUI element that is used at several different points in a swing application. When the "OK" button is pressed, I need to run a different code in each instance.

I went around this by passing an action listener in each case, but as I continue, it becomes messy. It would be preferable to pass the block to a method that is possible in Ruby. I am wondering if there is something similar but clean in Java.

Messiah code: Mostly because of the need to call methods on elements of a GUI object. If I pass the ActionListener in the constructor, the object does not exist yet. I can call the second method on each instance, but this is not preferred.

+4
source share
4 answers

The solution I came up with does not really affect the title of the question, but is great for my needs. Because:

  • In my case, the same functionality is always executed (for example, the onConfirm function), and this functionality is required in each instance.
  • Each instance requiring unique functionality really did not match the factory pattern.

I made my GUI element element:

abstract class Element extends JPanel { ... private final JButton button = new JButton("OK"); protected abstract void onConfirm(); public Element(){ this.button.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { onConfirm(); } }); ... } } 

With a few anonymous implementations of the inner class that allow me to access the internal elements of the GUI.

 this.getContentPane().add(new Element(){ @Override public void onConfirm() { doStuffWithCommand(); } }); 
0
source

You already have the right idea. The usual solution for passing arbitrary blocks of code into methods is the Command Template . If you can show an example of the "dirty" code that you have now, perhaps this will help you clear it.

Update Re: Messy Code

If I pass the ActionListener in the constructor, the object does not exist yet.

The actual code sample will help a lot to give a good answer. I suppose you might want to look at the Factory pattern ? In this case, I think more about the benefits of encapsulation than about the polymorphic benefits. Again, just guessing. Code search helps.

+3
source

Passing an ActionListener implementation is probably the best thing you can do right now.

Java 8 will provide support for closures, which will greatly simplify the implementation of interfaces with a single method with a single argument. But, with Java 7 barely coming out, it will be a few years for Java 8.

+1
source

Java does not support the idea of ​​code blocks (or functions, for that matter) as first-class citizens. That is why events are executed through classes that implement certain interfaces. It seems you are already doing something similar, so maybe you just need to create your own interface that supports the specific events that you want to support.

0
source

Source: https://habr.com/ru/post/1345761/


All Articles