2012-08-28 4 views
1

현재 j2me 응용 프로그램에서 작업 중이며 명령 단추를 다루는 데 어려움을 겪고 있습니다. 누군가 나를 도울 수 있습니까? 버튼은 두 번째 형식으로 지시한다고 가정했지만 클릭하면 작동하지 않습니다. 여기에 내 코드입니다 :J2ME 단추 명령이 작동하지 않습니다.

 import javax.microedition.midlet .*; 
     import javax.microedition.lcdui .*; 
     import javax.microedition.lcdui.StringItem; 
     import javax.microedition.lcdui.TextField; 
     import javax.microedition.lcdui.DateField; 
     import javax.microedition.lcdui.Command; 
     import javax.microedition.lcdui.Alert; 
     import javax.microedition.pim.PIM; 
     import javax.microedition.pim.PIMItem; 
     import javax.microedition.pim.PIMException; 
     import java.util.Date; 
     import java.util.Enumeration; 
     import javax.microedition.lcdui.Choice; 
     import javax.microedition.lcdui.List; 
     import javax.microedition.pim.ToDo; 
     import javax.microedition.pim.ToDoList; 
     import javax.microedition.lcdui.Displayable; 
     import javax.microedition.lcdui.Display; 
     import javax.microedition.lcdui.Form; 
     import javax.microedition.lcdui.CommandListener; 

     public class MainMidlet extends MIDlet implements CommandListener, 
     ItemCommandListener { 

     private Form aform, bform, addToDoForm; 
     private Command okCommand; 
     private Command exitCommand; 
     private Command cmdAddTodo; 
     private Command cmdretrieveTodo; 
     private Command cmdExit; 
     private Command backCommand; 
     private Command hllinkCommand; 
     private Command b1Command, b2Command; 
     private Display aDisplay; 
     private StringItem hlstringItem,hlstringItem2; 
     private StringItem b1stringItem, b2stringItem, b1stringItem2, b2stringItem2; 
     private Alert hlAlert; 
     private Alert b1Alert, b2Alert; 
     private TextField summaryField; 
     // Date field for Due data of ToDo. 
     private DateField dueDateField; 
     // Date field for end data of ToDo. 
     private TextField noteField; 
     // Text field to set priority of ToDo. 
     private TextField priorityField; 
     private List listTodos; 
     private ToDoList todoList; 
     private ToDo todo; 

     public MainMidlet() { 
     okCommand = new Command ("OK", Command.OK, 1); 
     exitCommand = new Command ("EXIT", Command.EXIT, 1); 
     backCommand = new Command ("BACK", Command.BACK, 1); 
     hllinkCommand = new Command ("LINK", Command.ITEM, 2); 
     b1Command = new Command ("BUTTON", Command.ITEM, 2); 
     b2Command = new Command ("BUTTON", Command.ITEM, 2); 

     aform = new Form ("CyberMe"); 

     // if click hyperlink "here", display anAlert 
     hlstringItem = new StringItem (null, "here", Item.HYPERLINK); 
     hlstringItem.setItemCommandListener (this); 
     hlstringItem.setDefaultCommand (hllinkCommand); 

     b1stringItem = new StringItem (null, "Make ToDo", Item.BUTTON); 
     b1stringItem.setItemCommandListener (this); 
     b1stringItem.setDefaultCommand (b1Command); 

     b2stringItem = new StringItem (null, "Set Alarm", Item.BUTTON); 
     b2stringItem.setItemCommandListener (this); 
     b2stringItem.setDefaultCommand (b2Command); 

     /*hlstringItem2 = new StringItem (null, "here", Item.HYPERLINK); 
     hlstringItem2.setItemCommandListener (this); 
     hlstringItem2.setDefaultCommand (hllinkCommand); 

     b1stringItem2 = new StringItem (null, "Make ToDo", Item.BUTTON); 
     b1stringItem2.setItemCommandListener (this); 
     b1stringItem2.setDefaultCommand (b1Command); 

     b2stringItem2 = new StringItem (null, "Set Alarm", Item.BUTTON); 
     b2stringItem2.setItemCommandListener (this); 
     b2stringItem2.setDefaultCommand (b2Command);*/ 


     hlAlert = new Alert ("Item.HYPERLINK", "You Can Call Me 800-81" 
     , null, AlertType.INFO); 
     b1Alert = new Alert ("Item.Button", "You click ToDo!" 
     , null, AlertType.INFO); 
     //b2Alert = new Alert ("Item.Button", "You click Alarm!" 
     //, null, AlertType.INFO); 


     aform.append ("What do you want to do?"); 
     aform.append (hlstringItem); 
     aform.append (b1stringItem); 
     aform.append (b2stringItem); 

     aform.addCommand (okCommand); 
     aform.addCommand (exitCommand); 
     aform.setCommandListener (this); 

     /*bform.append ("What do you want to do?"); 
     bform.append (hlstringItem2); 
     bform.append (b1stringItem2); 
     bform.append (b2stringItem2); 

     bform.addCommand (okCommand); 
     bform.addCommand (backCommand); 
     bform.setCommandListener (this); */ 

     } 

     /*public void SecondPage(){ 
     if(checkPIMSupport() == false) { 
     exitMIDlet(); 
     } 

     setComponents(); 
     } 

     /** 
     * Initializes components of MIDlet. 
     */ 
     public void setComponents() { 

     aDisplay = Display.getDisplay(this); 

     // Create form for adding ToDo. 
     addToDoForm = new Form("ToDo"); 

     // Add commands to form and set listener for it. 
     cmdAddTodo = new Command("Add Todo", Command.SCREEN, 0); 
     cmdretrieveTodo = new Command("Retrieve All Todos", Command.SCREEN, 0); 
     addToDoForm.addCommand(cmdAddTodo); 
     addToDoForm.addCommand(cmdretrieveTodo); 

     cmdExit = new Command("Exit", Command.EXIT, 0); 
     addToDoForm.addCommand(cmdExit); 

     addToDoForm.setCommandListener(this); 
     listTodos = new List("ToDo list", Choice.IMPLICIT); 
     backCommand =new Command("Back", Command.BACK, 0); 
     listTodos.addCommand(backCommand); 
     listTodos.setCommandListener(this); 

     try { 

     StringBuffer supported = new StringBuffer(); 

     // Get list of ToDos. 
     todoList = (ToDoList)PIM.getInstance().openPIMList(
     PIM.TODO_LIST, PIM.READ_WRITE); 

     // Create controls based on supported fields for ToDo. 
     if(todoList.isSupportedField(ToDo.SUMMARY) == true) { 
     summaryField = new TextField("Summary", null, 20, 
           TextField.ANY); 
     addToDoForm.append(summaryField); 
     } 

     else { 

     supported.append("Summary field\n"); 
     removeCommand(); 

     } 

     if(todoList.isSupportedField(ToDo.DUE) == true) { 
     dueDateField = new DateField("Date", 
           DateField.DATE_TIME); 
     dueDateField.setDate(new Date()); 
     addToDoForm.append(dueDateField); 

     } 

     else { 

     supported.append("Due date field\n"); 
     removeCommand(); 

     } 


     if(todoList.isSupportedField(ToDo.NOTE) == true) { 
     noteField = new TextField("Information", null, 20, TextField.ANY); 
     addToDoForm.append(noteField); 
     } 

     else { 

     supported.append("Note field\n"); 
     } 

     if(todoList.isSupportedField(ToDo.PRIORITY) == true) { 
     priorityField = new TextField("Priority", null, 20, 
           TextField.NUMERIC); 

     addToDoForm.append(priorityField); 
     } 
     else { 

     supported.append("Priority field\n"); 
     removeCommand(); 
     } 

     if(supported.length()!=0){ 

      StringItem si = new StringItem("ToDo field not supported", "");  
      si.setText(supported.toString()); 
      addToDoForm.append(si); 
     } 


     } catch(PIMException pimExc) { 
     // TODO: Handle error on working with PIM. 
     } 
     catch(SecurityException secExc) { 
     // TODO: Handle error on access to PIM. 
     } 
     catch(Exception exc) { 
     // If unknown error was caught, show it to the end user. 
     showAlert("Info", exc.toString()); 
     } 

     } 

     // Remove the command for adding ToDos 
     public void removeCommand(){ 
     addToDoForm.removeCommand(cmdAddTodo); 
     } 

     public void listToDos() { 

     Enumeration todos = null; 

     try { 
     todoList = (ToDoList) PIM.getInstance().openPIMList(PIM.TODO_LIST, PIM.READ_WRITE); 

     } catch (PIMException e) { 
     // Cannot open ToDo list 
     showAlert("Info", "Failed to open a ToDo list: "+e.toString()); 
     return; 
     } catch (SecurityException e) { 
     // User rejects application's request for reading ToDo list 
     showAlert("Info", "Reading ToDo List rejected: "+e.toString()); 
     return; 
     } 

     try { 
     // Get the enumeration of all ToDo elements 
     todos = todoList.items(); 

     } catch (PIMException e) { 
     // Failed to retrieve elements 
     showAlert("Info", "This application cannot retrieve ToDos: "+e.toString()); 
     } 

     if (listTodos.size() > 0) { 
     listTodos.deleteAll(); 
     } 

     while (todos.hasMoreElements()) { 
     todo = (ToDo) todos.nextElement(); 
     String todoInfo = null; 
     try { 
     todoInfo = todo.getString(ToDo.SUMMARY, PIMItem.ATTR_NONE); 

     } catch (Exception ex) { 
     showAlert("Info",ex.getMessage()); 
     continue; 
     } 
     if (todoInfo != null) { 
     listTodos.append(todoInfo, null); 
     }   
     } 
     } 

     /** 
     * Checks PIM support. 
     * @return - true if PIM is supported, false otherwise. 
     */ 

     private boolean checkPIMSupport() { 
     String propValue = System.getProperty("microedition.pim.version"); 
     if(propValue != null) { 
     return true; 
     } else { 
     return false; 
     } 
     } 



     private void getToDoList() { 
     listToDos(); 
     aDisplay.setCurrent(listTodos); 
     } 

     /** 
     * Adds ToDo to list of ToDos. 
     * Gets data for ToDo from addToDoForm controls. 
     */ 
     private void addToDo() { 

     try { 

     // Get list of ToDos. 
     todoList = (ToDoList)PIM.getInstance().openPIMList(
     PIM.TODO_LIST, PIM.READ_WRITE); 

     // Create new ToDo. 
     todo = todoList.createToDo(); 

     // Get data from controls 
     if(todoList.isSupportedField(ToDo.SUMMARY) == true) { 

     if(summaryField.size()==0){ 

     showAlert("Info", "Summary missing, please enter a summary"); 
     return; 
     } 
     String summary =summaryField.getString(); 
     todo.addString(ToDo.SUMMARY, PIMItem.ATTR_NONE, summary); 
     } else { 
     // At least summary must be supported. 
     closeToDoList(); 
     showAlert("Info", "Summary field for ToDo is not supported"); 
     } 

     if(todoList.isSupportedField(ToDo.DUE) == true) { 
     long startDate = dueDateField.getDate().getTime(); 
     todo.addDate(ToDo.DUE, PIMItem.ATTR_NONE, startDate); 
     } 

     if(todoList.isSupportedField(ToDo.NOTE) == true) { 
     String note = noteField.getString(); 
     todo.addString(ToDo.NOTE, PIMItem.ATTR_NONE, note); 
     } 

     if(todoList.isSupportedField(ToDo.PRIORITY) == true) { 

     if(priorityField.size()==0){ 

     showAlert("Info", "Priority is missing, please enter a priority"); 
     return; 
     } 

     else { 

      String location = priorityField.getString(); 
      int i=Integer.parseInt(location);    

      if(i > 9){ 

      showAlert("Info","Priority exceeded, please enter a priority between 0-9"); 
        return; 
      }     

      todo.addInt(ToDo.PRIORITY, PIMItem.ATTR_NONE, i);   
     } 
     } 

     // Commit ToDo. 
     todo.commit(); 

     // Notify user that ToDo was added 
     showAlert("Info", "ToDo was successfully added"); 

     } catch(PIMException pimExc) { 
     // TODO: Handle error on working with PIM. 
     showAlert("Info", pimExc.getMessage()); 
     } 
     catch(SecurityException secExc) { 
     // TODO: Handle error on access to PIM. 
     showAlert("Info", secExc.getMessage()); 
     } 

     catch(Exception exc) { 

     // TODO: Handle all other errors. 
     showAlert("Info", exc.toString()); 

     } 

     } 

     /** 
     * Shows alert with specified title and text. 
     * @param title - Title of alert. 
     * @param message - text of alert. 
     */ 
     private void showAlert(String title, String message) { 
     Alert alert = new Alert(title); 
     alert.setString(message); 
     alert.setTimeout(2000); 
     aDisplay.setCurrent(alert); 
     } 

     /** 
     * From MIDlet. 
     * Signals the MIDlet that it has entered the Active state. 
     */ 


     public void startApp() { 
     aDisplay = Display.getDisplay (this); 
     aDisplay.setCurrent (aform); 


     } 

     public void pauseApp() { 
     } 

     public void destroyApp (boolean unconditional) { 

     } 
     private void exitMIDlet() { 
     notifyDestroyed(); 
     } 

     private void closeToDoList() { 
     if (todoList != null) { 
     try { 

     todoList.close(); 
     } catch (PIMException ex) { 
     showAlert("Info","Error in closing ToDo list: "+ex.toString()); 
     } 
     } 
     todoList = null; 
     } 
     public void commandAction (Command c, Displayable d) { 

     if (c == exitCommand) { 
     destroyApp (false); 
     notifyDestroyed(); 
     } 
     if(c == backCommand){ 
     aDisplay.setCurrent(aform); 
     } 
     } 

     public void commandAction (Command c, Item i) { 

     if (c == hllinkCommand) { 
     aDisplay.setCurrent (hlAlert, aform); 
     } 
     if (c == b1Command) { 
     aDisplay.setCurrent (b1Alert, aform); 
     } 
     if (c == b2Command){ 
     aDisplay.setCurrent (addToDoForm); 
     } 

     } 
     } 

답변

3

즉각적인 실수 - 그리고 그 모든 문제의 가장 작은 - 당신이 commandAction(Command, Displayable)okCommand을 처리하는 것을 잊었다입니다.

결과적으로 사용자가 확인을 클릭하면 아무 일도 일어나지 않습니다. 단순히 처리 할 코드가 없기 때문입니다. 단지의 commandAction에 추가 - - 표시 가능하지 않은 항목을 다루는 하나에 -

이 실수 수정하기 쉬운 코드를 다음과 같이하면됩니다 :

 if(c == okCommand){ 
      // show whatever screen you need 
      aDisplay.setCurrent(new Form("whatever")); 
     } 

그러나 이것은 당신의 문제를 종료하지 않습니다 이와 같은 코드를 사용하면 미묘한 실수를 저지르고 이러한 문제를 해결할 수있는 머리가 깨질 수 있습니다. 우리가 먼저 나쁜 실수, 사소한 일에 완료 이제

은 사용자 작업의 지점에서 내가 catch 블록, 자바 같은 검색 웹을 언급하는 이유에 대한 catch 블록 (내 기록의 부족 예외를 삼키십시오).

이렇게하면 디버깅 할 때 일어나는 일을 파악하는 것이 불필요하게 어렵습니다. 위의 okCommand 처리가 누락 된 것과 같은 버그는 단순히 MIDlet을 실행하고 거기에 로깅이있는 경우 에뮬레이터 콘솔을 조사하여 쉽게 찾을 수 있습니다.

로깅을 권장하는 사용자 작업의 포인트는 이며, setCurrent을 호출 할 때 발생합니다. 개발할 때, 필요성을 느낄 곳을 자유롭게 추가하십시오 (캔버스를 사용하는 경우 keyPressed도 좋은 후보로 보입니다).

public class Log { 
    // utility class to keep logging code in one place 
    public static void log (String message) { 
     System.out.println(message); 
     // when debugging at real device, S.o.p above can be refactored 
     // - based on ideas like one used here (with Form.append): 
     // http://stackoverflow.com/questions/10649974 
     // - Another option would be to write log to RMS 
     // and use dedicated MIDlet to read it from there 
     // - If MIDlet has network connection, an option is 
     // to pass log messages over the network. Etc etc... 
    } 
} 


// ... other classes... 
    // ... 
    catch (Exception e) { 
     Log.log("unexpected exception: [" + e + "]"); 
    } 

    // ... 
    public void commandAction(Command c, Displayable s) { 
     Log.log("command: [" + c.getCommandLabel() 
       + "] at screen: [" + d.getTitle() + "]"); 
     // ... 
    } 

    // ... 
    public void commandAction(Command c, Item i) { 
     Log.log("command: [" + c.getCommandLabel() 
       + "] at item: [" + i.getLabel() + "]"); 
     // ... 
    } 

    // ... 
    Log.log("set current: [" + someDisplayable.getTitle() + "]"); 
    display.setCurrent(someDisplayable); 
    // ... 

    protected void keyPressed(int key) { // in Canvas 
     Log.log("key pressed: [" + getKeyName(key) + "]"); 
     // ... 
    } 

코드의 또 다른 정말 정말 나쁜 실수는 그것이 God object 점이다. 이로 인해 수정과 디버그가 불필요하게 어렵습니다. 작은 클래스로 응용 프로그램을 분할하면 한 곳에서 모두 유지할 필요가 없습니다.

처음에는 MainMidlet에서이를 구현하는 대신 CommandListener와 ItemCommandListener를 별도의 클래스로 이동하는 것을 고려하십시오. 하나 이상의 Item/CommandListener가있을 수 있습니다 (예 : 각 화면마다 하나씩).

aform의 내용과 관련된 코드를 별도의 클래스로 분할하십시오. bform, addToDoForm, listTodos와 동일합니다. 기타

+0

고맙습니다. 나는 많이 배웠다. 방금 j2me를 시작했는데 좋은 도움이되었습니다! – drayl