Tuesday, 15 February 2011

java - How to return String in anonymous class for a method returning void -



java - How to return String in anonymous class for a method returning void -

i'm bit confused. have following:

public static string showinputdialog() { form frm = new form(); final command cmd = new command("ok"); final textfield txt = new textfield("enter text", null, 1024, 0); frm.addcommand(cmd); frm.append(txt); frm.setcommandlistener(new commandlistener() { public void commandaction(command c, displayable d) { if (c == cmd) { homecoming txt.getstring(); // error !! } else { homecoming null; // error !! } } }); }

as can see, want homecoming input dialog string, while anonymous class method should homecoming void. how can resolve problem?

this not work expected.

i see there solutions, sense bit more give-and-take going on might helpful.

when phone call frm.setcommandlistener(new commandlistener() { ... }) code presents user dialog can type in text , submit, code not stop , wait until user finishes. instead code continues execute - without yielding result. after user finished typing , submits, called process result - might happen much later, or not @ all.

i guess have code calling method like:

public void somemethod(int foo, string bar) { [...] string result = myinputform.showinputdialog(); // result system.out.println("hey, got result "+ result); [...] }

instead need reorganize this. first write helper class handling result:

public static class mycallback {

public mycallback(... /* here pass in need process result*/) { ... remember necessary stuff in instance variables } public void processresult(string result) { // result system.out.println("hey, got result "+ result); [...] }

}

then calling side just:

public void somemethod(int foo, string bar) { [...] myinputform.showinputdialog( new mycallback(... here pass in stuff ...) ); [...] }

and actual code has changed to:

public static string showinputdialog(final mycallback callback) { form frm = new form(); final command cmd = new command("ok"); final textfield txt = new textfield("enter text", null, 1024, 0); frm.addcommand(cmd); frm.append(txt); frm.setcommandlistener(new commandlistener() { public void commandaction(command c, displayable d) { if (c == cmd) { homecoming callback.processresult(txt.getstring()); } else { return; // or omit else part } } }); }

two issues:

this way of programming feels pretty backwards, way works. what feels not right need define sec helper class aside of commandlistener. not style. hope can improved, not see finish code (which much info anyway), have leave improve code , rid of clutter. while sense want have modular, reusable input dialog helper, might not best approach; improve define form,textfield , command straight need result , running. create reusable in sec step after running.

java

No comments:

Post a Comment