Shaaf’s Blog
msgbartop
Another bit in the wall
msgbarbottom

17 Nov 08 Command, Singleton, JMenuItem, JButton, AbstractButton – One Listener for the app

Here I would like to demonstrate a simple use of JMenuItems being used with Single Listener for the entire system.
A simple sample of use would probably be SingleInstance Desktop Application.

Lets see how that is done here.

1. First lets create a OneListener class that should be able to listen to ActionEvents and also be able to add Commands to itself. Please refer to my previous post on Command,Singleton if you would like to see more about this patterns and there usage.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.shaafshah.jmenus;
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
 
import javax.swing.AbstractButton;
 
// Implements the ActionListener and is a Singleton also.
 
public class OneListener implements ActionListener{
 
	private static OneListener oneListener = null;
 
	// Holds the list of all commands registered to this listener
	private ArrayList<Command> commandList = null;
 
	// A private constructor
	private OneListener(){
		commandList = new ArrayList<Command>();
	}
 
	// Ensuring one instance.
	public static OneListener getInstance(){
		if(oneListener != null)	
			return oneListener;
		else return oneListener = new OneListener();
	}
 
	// Add the command and add myself as the listener
	public void addCommand(Command command){
			commandList.add(command);
		    ((AbstractButton)command).addActionListener(this);
	}
 
 
	// All Events hit here.
	@Override
	public void actionPerformed(ActionEvent e) {
		((Command)e.getSource()).execute();
	}
 
}

In the above code, the addCommand method adds the command Object and adds a listener to it.
Now how is that possible.
Basically because I am categorizing my UI objects as Commands with in the system having some UI. And I am also assuming that these commands are Currently AbstractButton i.e. JMenuItem, JButton. Lets have a look at the Command Interface and its Implementation.

1
2
3
public interface Command {
	public void execute();	
}

And the implementation, note that the Command is an interface where as the class is still extending a UI object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import javax.swing.JMenuItem;
 
public class TestCmd extends JMenuItem implements Command{
 
	public TestCmd() {
		super("Test");
		OneListener.getInstance().addCommand(this);
	}
 
	@Override
	public void execute() {
		System.out.println("HelloWorld");
	}
}

Personally don’t like calling the OneListener in the constructor of the class but just for the sake of simplicity of this post I have left it that way. There are many different ways to omit it.

So the TestCmd is a JMenuItem but is also a Command and thats what the OneListener understands.
As this commads Listener is also OneListener all ActionEvents are thrown there and from there only the Command.execute is called on.

So now you dont have to worry about what listeners are you in. The only thing you know is that when execute is called you need to do your stuff.

You can download the code from Here.

Hope this helps.

Tags: , , , , , , , , , , , , , , ,

31 Oct 08 Command

By using the command pattern you are seperating the operation from the invoking object. And just because of that it becomes easier to change the command without chagning the caller/s.
This means that you could use Command pattern when you might have the following situation

You want to parameterize objects to perform an action
You want to specify, execute and queue requests at different times.

Just to quickly start you need a command object, An interface will keep it easy going in this case, thus providing you with the option of extending other classes e.g. Swing MenuItem or Button.
Below the execute Method is the one invoked to do something when this command is called or asked to do its stuff.
Where as the getCommandName is assumed as a unique name how ever I am sure we can always come up with a better implementation for uniqueness.

1
2
3
4
5
6
public interface Command {
 
    public void execute();
    public String getCommandName();
 
}

And example implementation of the Command should look as follows
A Command Name, and and execute Method to tell what happens when this command is called.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class ForwardCmd implements Command {
 
   private String COMMAND_NAME = "Back";
 
   public BackCmd() {
       super();
   }
 
   public String getCommandName() {
       return COMMAND_NAME;
    }
 
    public void execute() {
        System.out.println("Your wish, my command");
    }
}

The command manager is the controller in this case. It registers command objects. the “registerCommand” will simply take a command and store it in a list or something alike. This means you could load it out of a jar file, or an xml or path and just pass the object to the “registerCommand” AS a command offcourse.

the “execute” Command will simply execute the Command passed to it.

And the “getCommand” returns a command by looking up a COMMAND_NAME. So if you provide a name to it through you system it should give you an object of type Command and simple pass it to execute. Again this would be a controller logic and not the client one.

1
2
3
4
5
6
7
public abstract class AbstractCommandManager {
 
    public abstract void registerCommand(Command command);
    public abstract Collection getAllCommands();
    public abstract void execute(Command command);
    public abstract Command getCommand(String name);
}

Tags: , , , , , , , , , ,

29 Oct 08 Implementing the adapter

Typically when implementing an interface you would have to implement all the methods that exist in that interface. A very good example is the MouseListener in the java Swing. When you need to implement more then one method where as typically you might be catching only one of them. Saying that you would also find a Mouse Adapter provided as well. Some of us use that often. And that is part of the Adapter pattern. It makes life easier for me sometimes.

Adapter a structural pattern will let you adapt to a different environment. The joining between different environment is called Adapter. Thus basically giving others the interface that they expect or vice versa when your program becomes the client.

For example the following class expects that the implementing class should be implementing all three methods.

1
2
3
4
5
6
7
8
9
public interface RecordListener {
 
public void eventPrePerformed(RecordEvent recordEvent);
 
public void eventPerformed(RecordEvent recordEvent);}
 
public void eventPostPerformed(RecordEvent recordEvent);
 
}

So lets say our implementing class is a rude one and only wants to implement one method. What do you do as an API designer. hmmm

Thats where we step in with the Adapter.

1
2
3
4
5
6
7
8
9
10
11
12
13
public abstract class RecordAdapter implements RecordListener {
 
public void eventPrePerformed(RecordEvent recordEvent) {}
public void eventPerformed(RecordEvent recordEvent) {}
public void eventPostPerformed(RecordEvent recordEvent) {}
 
}
 
public MyAdapterImpl extends RecordAdapter{
 
public void eventPerformed(RecordEvent recordEvent){}
 
}

Now the only thing left to do is use the adapter. And override any method that you might need .

1
2
3
4
5
6
7
8
9
public MyClientClass {
 
public MyClientClass(){
 
this.addRecordListener(new MyAdapterImpl());
 
}
 
}

Tags: , , , , , , , , , , ,