Pass a block to a method in Java - java

I have a GUI element which is used across several different points in a swing application. When the 'OK' button is pushed I need to run different code in each instance.
I have gotten around this by passing an action listener in each case but as I continue this is getting messy. It would be preferable to pass a block to a method as is possible in Ruby. I am wondering if something similar but clean exists in Java.
Messy code:
Mostly due to needing to call methods on elements of the GUI object. If I pass the ActionListener in the constructor the object doesn't exist yet. I can call a second method in each instance but it isn't preferable.

You have the right idea already. The usual solution for passing arbitrary blocks of code into methods is a Command pattern. If you can show an example of the "messy" code you have now, it might be possible to help you clean it up.
Update Re: Messy Code
If I pass the ActionListener in the constructor the object doesn't exist yet.
An actual code sample would help a lot in giving a good response. At a guess, I would say perhaps you want to look at a Factory pattern? In this case, I'm thinking more of the encapsulation benefits than the polymorphic benefits. Again, just guessing. Seeing code helps.

Passing an ActionListener implementation is probably the best you can do right now.
Java 8 will provide support for "closures", which will greatly streamline the implementation of interfaces with a single, one-argument methods. But, with Java 7 barely coming out, it will be a few years for Java 8.

Java does not support the idea of code-blocks (or functions, for that matter) as first-class citizens. That's why events are done via classes that implement particular interfaces. You seem to be doing something similar already, so perhaps you just need to create your own interface that supports the particular events you want to support.

The solution I have gone with doesn't really address the title of the question properly but suited my needs perfectly. Because:
In my case it is always the same functionality being parsed (ie, the onConfirm functionality) and this functionality is required in each instance.
Each instance requiring unique functionality did not really suit a factory pattern.
I have made my GUI element abstract:
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 several anonymous inner class implementations which each allow me to access the internals of the GUI Element.
this.getContentPane().add(new Element(){
#Override public void onConfirm() {
doStuffWithCommand();
}
});

Related

Which design pattern can I use to supply several methods that create "pre-configured" UI components

Disclaimer: I’m new to programming in Java and working with “extreme” OOP in general, so the answer to this might be really simple.
I’m creating a user interface in Vaadin, a Web application framework that supplies lots of useful components for me. Often, I’m not entirely happy with the default settings for these components.
For example, if I want every TextField component to fire value change events immediately when the field loses focus. There are similar settings for UploadField, TextArea, ComboBox etc. that I want to set on every instance of those classes.
Currently, what I have looks like this:
public class ConfiguredComponents {
public static TextField createConfiguredTextField(String caption) {
TextField field = new TextField(caption);
field.setImmediate(true);
field.setSomeOtherOptions();
...
return field;
}
public static UploadField createConfiguredUploadField(...) {
...
}
// etc.
}
This doesn’t feel like a class at all! It’s just a collection of static methods, which I’ve been told to avoid. Plus, I would like to place the logic for each component in a separate file. The configuration gets quite involved sometimes, and it just makes more sense that way: these are all very tiny self-contained bits of logic.
Here are the solutions I’ve considered:
Keep it simple: I could get rid of ConfiguredComponents, and just make one big package containing small factory classes. For example, myproject.ui.components.TextFieldFactory knows how to create a configured TextField and nothing more.
Pros:
The ugly ConfiguredComponents class is gone.
All of the logic is in separate files.
Cons:
There’s no single interface to the creation of my configured components; the only thing keeping them together is the fact that they’re in the same directory. Basically, I have to expose a lot of tiny classes, and there’s no single class or object managing them. (This intuitively feels like a pretty bad thing, but I don’t know if it really is.)
There’s also no way to override or extend static methods, so “faking” UI stuff for testing gets harder.
The Abstract Factory pattern: I make ConfiguredComponents into an AbstractComponentFactory that manages a lot of smaller factories.
Pros:
All of the logic is in separate files.
The logic that actually configures my components is fully behind-the-scenes.
Cons:
I would need an instance of AbstractComponentFactory every time I want to create a component anywhere in the code for my views. This means either keeping a singleton object, which has a lot of downsides, or creating a new AbstractComponentFactory() every time.
I have to write new code in two or three places, instead of just one, if I wish to add new components to my little “library”.
Some other design pattern I don't know about: I’ve read a bit about Builder, and Facade, which feel like they might apply here, but I don’t understand them very well.
How would you approach this design decision?
If your components can be inherited, then go ahead; for each component that you want to alter default settings, create a new derived class and config settings in constructors. Otherwise,
Abstract factory pattern is a good choice. I think you are misunderstanding about this pattern. AbstractComponentFactory is just an interface, it does not manage anything. This interface looks like this:
interface AbstractComponentFactory {
public TextField createTextFiled(...);
public UploadField createUploadFiled(...);
...
}
In your situation, I think you need only one implementation for this factory:
class MaurisComponentFactory implements AbstractComponentFactory {
public TextField createTextFiled(...) {
new ... config ... return;
}
public UploadField createUploadFiled(...) {
new ... config ... return;
}
...
}
As you said, we should neither use Singleton nor create new MaurisComponentFactory everytime. Instead, we should create only one instance in the main() method, and then try to inject this instance to every place that need to create components.
One possible approach i can think think is to use AbrstractFactory with Service Locator or Registry patterns
Since you have myriad objects that does not have complicated instantiation process (if so resort to build pattern), you create objects with Abstract Factory and register them in registry. And resolve them as needed where ever you are.
or you may resort simple IOC container where your entire application is wrapped around

Organize Code for GUI and ActionListener in Java [duplicate]

This question already has answers here:
Implement an interface and override methods in Java?
(6 answers)
Closed 4 years ago.
I am new to Java and was wondering how I would go about implementing ActionListener code in my project. I am aware of inner classes and the implementation the ActionListener interface, but going down that road makes the code look more messy than it probably should.
Would I write another class ActionCode that implements ActionListener and extends GUI or what road would you suggest and why?
What's your best practice advise on that and where can I find those guidelines?
(The JavaDoc seems to explain the basic implementation of ActionListeners, but doesn't seem to have any model how to organize large/medium projects).
In my opinion, there is no "best" approach. Even the code examples from sun/oracle tutorials use different ways to implement listeners.
From my experience, a good approach is:
Use anonymous implementations: People know this pattern and will quickly recognize it. It helps the reader to understand the code if there is a common way to do things
Have a special method, which only handles the listeners (e.g. private void addListeners()): Again, this helps everyone to recognize it and to know where to search for all the logic
Keep the listeners simple. This means less than 5-10 lines of code. If you need more complex logic, call a method.
Keep the number of listeners small. If you need > 50 listeners, you should probably refactor your view. If you need more than 10, you could think about refactoring.
Beside this general points, there are always exceptions. Like if you have a lot of Components with the same behavior, you could write a generic listener with a switch/case. (Typical example: buttons from a calculator or menu buttons).
Or if you have the same logic for multiple components, you could use a specific class.
And so on.
And just to mention it, because there are some examples in the sun/oracle tutorials: Try to avoid implementing a listener interface with the view class itself. This could be ok if you have only one listener, but it is most of the times awful for multiple events from multiple source with different behavior.
Code style can be a matter of personal taste, but modern literature suggests it's more than that. Let the chapter on Classes in Clean Code show you the way.
Classes Should Be Small!
The first rule of classes is that they should be small. The second rule
of classes is that they should be smaller than that. No, we’re not
going to repeat the exact same text from the Functions chapter. But as
with functions, smaller is the primary rule when it comes to designing
classes. As with functions, our immediate question is always “How
small?” With functions we measured size by counting physical lines.
With classes we use a different measure. We count responsibilities...
The Single Responsibility Principle (SRP) states that a class or
module should have one, and only one, reason to change. This principle
gives us both a definition of responsibility, and a guidelines for
class size. Classes should have one responsibility—one reason to
change...
The problem is that too many of us think that we are done once the
program works. We fail to switch to the other concern of organization
and cleanliness. We move on to the next problem rather than going back
and breaking the overstuffed classes into decoupled units with single
responsibilities. At the same time, many developers fear that a large
number of small, single-purpose classes makes it more difficult to
understand the bigger picture. They are concerned that they must
navigate from class to class in order to figure out how a larger piece
of work gets accomplished. However, a system with many small classes
has no more moving parts than a system with a few large classes. There
is just as much to learn in the system with a few large classes. So
the question is: Do you want your tools organized into toolboxes with
many small drawers each containing well-defined and well-labeled
components? Or do you want a few drawers that you just toss everything
into?
Every sizable system will contain a large amount of logic and
complexity. The primary goal in managing such complexity is to
organize it so that a developer knows where to look to find things and
need only understand the directly affected complexity at any given
time. In contrast, a system with larger, multipurpose classes always
hampers us by insisting we wade through lots of things we don’t need
to know right now. To restate the former points for emphasis: We want
our systems to be composed of many small classes, not a few large
ones. Each small class encapsulates a single responsibility, has a
single reason to change, and collaborates with a few others to achieve
the desired system behaviors.
So, based on these heuristics, Nested Classes break SRP. They should almost never happen. Instead, have your GUI classes include instance members of the ActionListeners they register. Keep the listeners in a separate *.listener package. Use interfaces to make them replaceable (Strategy Pattern) wherever deemed effective.
Java and Swing encourage lots of little objects like Listeners and Actions. It's a lot of boiler-plate, but that's the way Java is. There's little benefit in fighting it.
Creating anonymous listeners inline is fairly painless:
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ok();
}
});
But, you often need to reuse actions, say to assign the same action to a menu and a button. You might put them in your main application window as inner classes:
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class MainWindow extends JFrame {
ZapAction zapAction;
public MainWindow() {
setSize(new Dimension(200,200));
zapAction = new ZapAction();
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Foo");
menu.add(new JMenuItem(zapAction));
menuBar.add(menu);
setJMenuBar(menuBar);
JButton zapButton = new JButton(zapAction);
add(zapButton);
}
public void zap() {
// do some zapping
System.out.println("Zap!");
// maybe we're all done zapping?
zapAction.setEnabled(isZappingPossible());
}
public boolean isZappingPossible() {
// determine if there's zapping to be done
return Math.random() < 0.9;
}
class ZapAction extends AbstractAction {
public ZapAction() {
super("Zap");
putValue(AbstractAction.SHORT_DESCRIPTION, "Zap something");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(
KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
putValue(AbstractAction.SMALL_ICON,
new ImageIcon(MainWindow.class.getResource("/icons/zap.png")));
setEnabled(true);
}
public void actionPerformed(ActionEvent e) {
zap();
}
}
}
public class Zap {
public static void main(String[] args) {
MainWindow mainWindow = new MainWindow();
mainWindow.setVisible(true);
}
}
Here, ZapAction is package-private visibility. I put all the UI code in it's own package (say org.myorg.myproject.ui). So, all the UI objects have access to the actions.
In a complex swing app, I've gone as far as to create a UI facade layer, which makes a nice place for the actions and all the code that wires them up to various controls. It also makes a convenient place for external code to interact with the UI, keeping UI code isolated from core application code.

define button actions in inner class Vs define button actions in public class in swing

I have a dialog, which have four buttons say New, Save, Delete, Cancel. Now each of these need to perform their action. So I have defined a separate class which implements an ActionListener. I have used this class to perform each of the button action.
public class MyClass implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().toString() == "OK") {
// Code
} else if( .. ){
}
}
}
What I have done is, I defined an inner class which I used to do the same functionality. But what I was not getting is, is it best practice to write a separate class or is it best to use inner class. I was suggested to write in a public class so tomorrow some one can use this class to perform their action. So I have the following questions,
If the functionality is not called by any object (which I can't say) then I can write it in inner class? OR
Is it a good practice always to write inner class which performs the actions of that dialog?
There is no general answer to these questions. If the code in actionPerformed() is one line, writing a whole class file is usually overkill.
If the code is more complex, it might be suitable to reuse but as the code grows, it also gets more specific (so you can't reuse it anymore).
Try to follow this approach:
Build your application from simple blocks that are independent of each other.
Configure the application by writing code that connects the blocks.
So in your case, you could have helper methods which do the work. Wrap them in Swing Actions; this allows you to use them in all kinds of buttons and menus.
Try to move as much work as possible into the helpers so that the actions become really simple. If in doubt, ask yourself: Is this code part of the work? Does everyone need to do this?
If yes, then the code should go into a work/helper class.
If it's things like UI related checks (visible/enabled), conversion (string to number), validation, etc., it should go into the action.
When you talk about defining an inner class for a GUI listener, I think immediately of using anonymous classes to do the job:
newButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// do the work for a button press
}
});
// similarly for save, cancel, delete buttons:
saveButton.addActionListener(
new ActionListener()
{
// ...
You'll often see this, and I often use this in my own code.
Which you use depends on the structure of your code, for instance:
how much work each listener needs to do
how much code is shared between the handlers
If each handler is short (e.g. just one method call, with all the real work handled within another class method), I'll use anonymous classes this way. But it does look goofy: unfortunately java requires us to define an object to employ a callback method.
It's also a matter of personal preference and coding style.
However, I'd rarely make a new top-level class for a GUI handler as in your example: even if I separate out the class so that I use the same class for each button, I'd define the class within the class file controlling the buttons, either as a non-public top-level class, or as an inner (non-anonymous) class. If the complexity of a GUI callback grows to the point that it deserves a separate class, I'd start looking for places to refactor.
proper way should be Swing Action(mentioned in comment by #Robin), for JButtons Components as most scalable choice, with implementations of interesting methods
most complex GUI is there way to add EventHandler, which fired event and could be compare in String value

Objective-C delegates vs Java listeners

I've read a bunch of articles and readings on Objective-C delegates, trying to understand them. Coming from Java, they seem very much like Java listeners. For example, let's say I had a button in Java. When the button is pushed, I want something to happen. My code might look something like this:
ButtonListener myButtonListener = new ButtonListener();
someButton.addActionListener(myButtonListener);
...
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
}
}
Something like that. In objective-c it seems that I would do something along the lines of calling a setDelegate method for my button and passing it the "listener" as a delegate. The actual button class would then probably check if that delegate responded to some selector (ie. actionPerformed). If I'm thinking about this the right way, it does seem like delegates are just like listeners. Is that correct? Are there any major differences?
Thanks!
You're pretty much on the button there. The only real difference is delegates in obj-c generally implement multiple functions to perform various actions on events regarding the object they are delegating. For example, the UITextViewDelegate has the methods:
– textViewShouldBeginEditing:
– textViewDidBeginEditing:
– textViewShouldEndEditing:
– textViewDidEndEditing:
The only real difference I've found is you can't create your delegates inline, the way you can in java like:
someButton.setOnClickListener ( new View.OnClickListener {
#Override
public void onClick() {
//do stuff
}
});
they are similar, but not identical. a delegation pattern has broader definition, and often implementation defined tasks which can extend beyond listening alone. the tasks can include listening, or the delegate's implementation may be defined as listening (exclusively).
objc delegates are often used to avoid subclassing, and to serve as listeners or data providers. what a delegate does is defined by the protocol - it can serve as much more than a listener. so a delegate could be a data source/provider. it's just a means to offload implementation to another class, to remove from the class what is frequently customized, app-specific implementation.
NSButton/UIButton's already been specialized for this case via target+action mechanisms. you'd use target+action for this specific case.
Delegate is similar as listener or observer, protocol is similar as interface except protocol can define optional functions (aka messages). In Objective C, you can augment an existing class (without its source code) using category to adopt a protocol and make it a delegate, so that you don't need to create new anonymous inner classes at all. You can't do that in Java.
I think that a better Java analog to .NET delegates would be found in the java.util.concurrent pagkage: Callable, Future, Executor.

What is the common way to program action listeners?

I just started to learn how to use action listeners. To my understanding it works in the following way:
There are some classes which contains "addActionListener" method by default (for example classes for buttons).
Using this method we add an action listener to an object. For example: listenedObject.addActionListener(listeningObject).
When an action with the "listenedObject" is performed, the "actionPerformed" method of the "listeningObject" will be called. So, it means that when we program a class for the listeningObject, we need to put there "actionPerformed" method.
What is not clear to me, should we create a new class for every object that we want to listen. It does not seem to me as an elegant solution. On the other hand, if we have one action listener class for all (or at least many) object, than we have a problem since a instance of this class will not know which object is calling the "actionPerformed" method (and we need to know that since actions performed by the actionPerformed differs depending on who is called for this method).
In my opinion, for every listened object we need to create are "personal" action listener and we can do it by setting a specific value to the corresponding field of the action listener. But I am not sure that it is a standard way to go? How do usually people do it?
The most common way to handle this - judging from my own personal experience - is to simply create an anonymous inline class. Like this:
listenedObject.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
// Your action handling code in here
}
});
And often I've seen people place a call out to a method of the object containing the listenedObject. For example, in a Dialog that has a button:
myOkayButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
okayButtonPressed();
}
});
Then later in the dialog class:
private void okayButtonPressed() {
// Do what we need to do
}
Personnaly, when possible, i prefer to use an Action class (as an example a subclass of AbstractAction) instead of simply relying on an action listener. This way, I can provide the originating widget a name, an icon, a tooltip, and so on ...
The way I have always found useful (for navigation purposes) is to create an anonymous inner class which then delegates to the outer class:
listenedObject.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
listenedObject_actionPerformed(evt);
}
});
private void listenedObject_actionPerformed(ActionEvent evt) {
//Your handling goes here
}
It is then much easier to get to your handling code in an IDE using a structural lookup (CTRL+F12 in IDEA, CTRL+O in Eclipse).
The problem of using a single class (like a GUI MyCoolPanel) as the common listener to a bunch of its components (buttons etc) is that the actionPerformed method then has a lot of ugly if-else comparisons to figure out which button has actually been pressed - not very OO at all!
You certainly should not get overly worried about the performance aspects of this kind of thing - they are likely to be negligible in the extreme! Premature optimization is famously a bad thing
The way I have always found useful is to create a separate class which implements the ActionListener interface and all the other methods necessary to carry the action. This way, an action is not tied to a specific object and can be triggered from a button, a menu, etc. A little bit like the Command pattern I guess. It keeps the code simple.
Anonymous classes aren't reusable.
Redirection to the object containing the listenedObject leads to gigantic classes that are hard to maintain.
Beware that methods removeActionListener exists for a reason. You can skip listeners clean up if objects you listen to will die with object that handles events. But if your component listens the model supplied from external source, you should add your listeners in addNotify and remove them in removeNotify methods. Otherwise you may have a memore leak.
Maybe it's not actually at the moment, but I believe that in the nearest future (after Java 7 release) something like this would be the common way:
listenedObject.addActionListener ( #{doSmth();} );

Categories