I’m currently working on a small console application. This application is based on a MVC architecture. My controller add his own ActionListener to the view it manages. My ConsoleView do not extends any Swing or Componenent that allows it to have the method addActionListener to it. This is the code of my ConsoleView which has to be run from the command shell and waits for user input.
public class ConsoleView implements InterfaceView {
private Console c = null;
public ConsoleView() {
c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
String input;
do {
input = c.readLine();
} while (!parse(input));
}
/**
* Parse the input and returns true if the input has been successfully
* parse;
*
* @param input
* @return
*/
public static boolean parse(String input) {
if (input == null || input.equals(""))
return false;
input = input.trim();
int separator = input.indexOf(' ');
String cmd, arguments;
if (separator == -1) {
cmd = input;
arguments = null;
} else {
cmd = input.substring(0, separator);
arguments = input.substring(separator + 1);
}
Commands command;
try {
command = Commands.valueOf(cmd);
} catch (IllegalArgumentException ex) {
command = Commands.help;
}
String print = "You used " + cmd + " with arguments :" + arguments;
switch (command) {
case startvm:
break;
case stopvm:
break;
case list:
break;
case help:
break;
case exit:
return true;
default:
break;
}
System.out.println(print);
return false;
}
public static enum Commands {
stopvm, startvm, list, help, exit
}
//cal comes from my controller
public void addCommandListener(ActionListener cal){
//This is where i would do this.addActionListener(cal)
}
}
I would also want to be able to trigger these events in the parse method so the controller does what it has to do when the listener is noticed that an event has been triggered.
Thanks a lot. If you have an alternative option on how to do it, go ahead I’ll listen!
P.S. my boss wants to use that command prompt, thats why no Swing interface !!
Nothing prevents you from implementing the Observer pattern in any kind of classes!
You can reuse the listener interfaces of Swing if you want or create your own. Then you have to add a register and unregister method to your observable class, that basically adds and removes the listener object to a list; and a method that fires the change events (that is, calls the methods on the registered listeners with the relevant parameters).
There is a problem though with your current code, and is that the
parsemethod isstatic, you should make it non static so it knows about the list of listeners of the console view.