J2ME按钮命令不起作用 [英] J2ME button command not working

查看:95
本文介绍了J2ME按钮命令不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发j2me应用程序,并且很难处理命令按钮.有人可以帮帮我吗.该按钮应该以第二种形式指向,但是当我单击它时,它不起作用.这是我的代码:

I'm currently working on an j2me application and I'm having a hard time dealing with command button. Can someone please help me. The button was suppose to direct in a second form but when I click it, it's not working. Here's my code:

        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-8101234" 
        , 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);
        }

        } 
        }

推荐答案

您的直接错误-这是您所有问题中的最次要-是您忘记了处理commandAction(Command, Displayable).

Your immediate mistake - and that is the most minor of all your issues - is that you forgot to handle okCommand in the commandAction(Command, Displayable).

结果,当用户单击确定"时,什么也没发生-仅仅是因为没有代码来处理此问题.

As a result, when user clicks OK, nothing happens - simply because there's no code to handle this.

这个错误很容易解决-只需添加到commandAction中-放入处理Displayable not Item的错误中,如下所示,代码就完成了:

This mistake is easy to fix - just add into commandAction - into the one that deals with Displayable not Item - code like below, and you're done:

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

但这不会结束您的麻烦,因为使用这样的代码,您注定会犯出细微的错误并为解决这些错误而伤脑筋.

But this will not end your troubles, because with code like this you're effectively doomed to make subtle mistakes and break your head fixing these.

现在我们已经完成了一些小事情,首先,您的错误是在用户操作时和catch块内缺少日志记录(关于为什么我提到catch块,搜索在Web上查找 Java吞咽异常).

Now that we're done with minor thing, first of your bad mistakes is lack of logging at the points of user actions and within catch blocks (for why I mention catch blocks, search Web for something like Java swallow exceptions).

这使您不必要地难以确定调试时正在发生的事情.只需运行MIDlet并查看模拟器控制台(如果其中有日志记录),就很容易找出像上面的okCommand那样缺少处理的错误.

This makes it unnecessarily difficult to figure what's going on there when you debug. Bugs like missing handling of okCommand above would be quite easy to find out by simply running MIDlet and looking into emulator console if there was logging there.

commandAction之内以及调用setCurrent时,我建议记录日志的用户操作要点.在开发时,可以随意在需要的地方添加更多内容(如果使用Canvas,keyPressed看起来也很适合这样做).

Points of user actions where I'd recommend logging are within commandAction and when invoking setCurrent. When developing, feel free to add more where you feel the need to (if you use Canvas, keyPressed looks like a good candidate for that, too).

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) + "]");
        // ...
    }

您的代码中的另一个真的很糟糕错误是,这是一个上帝对象.这使得修改和调试变得不必要地困难.将您的应用程序拆分为较小的类,并不需要将其全部放在一个地方.

Another really really bad mistake in your code is that it's a God object. This makes it unnecessarily difficult to modify and debug. Split your application to smaller classes, there is no real need to keep it all in one place.

首先,请考虑将CommandListener和ItemCommandListener移到单独的类中,而不要让MainMidlet实现它们.请记住,Item/CommandListener可能不止一个,例如每个屏幕一个.

For a start, consider moving CommandListener and ItemCommandListener into separate classes instead of making MainMidlet implement these. Keep in mind that there could be more than one Item/CommandListener, eg one per each screen.

将与aform内容相关的代码拆分为一个单独的类.与bform,addToDoForm,listTodos相同.等等等

Split the code that is related to contents of aform into a separate class. Same to bform, addToDoForm, listTodos. Etc etc.

这篇关于J2ME按钮命令不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆