views:

242

answers:

2

I've developed UI application in blackberry.
On Button Click event I want to display result of adding two number.
How to handle this event in java app of Blackberry?

+2  A: 

Hi!
Best option to consume click event in ButtonField is to use FieldChangeListener. Just implement FieldChangeListener interface and apply ButtonField.setChangeListener():

class MenuScreen extends MainScreen implements FieldChangeListener {
    EditField mNumberAEditField;
    EditField mNumberBEditField;
    ButtonField mAddButtonField;
    public MenuScreen() {
        super(DEFAULT_CLOSE);
        mNumberAEditField = new EditField("A:", "2", 10, 
                EditField.FILTER_INTEGER);
        add(mNumberAEditField);
        mNumberBEditField = new EditField("B:", "2", 10, 
                EditField.FILTER_INTEGER);
        add(mNumberBEditField);
        mAddButtonField = new ButtonField("A + B", 
                ButtonField.CONSUME_CLICK);
        add(mAddButtonField);
        mAddButtonField.setChangeListener(this);
    }

    public void fieldChanged(Field field, int context) {
        if(field == mAddButtonField)
        {
            showAddResult();
        }
    }

    private void showAddResult() {
        String message = "";
        String aStr = mNumberAEditField.getText();
        String bStr = mNumberBEditField.getText();
        if(aStr == "")
            message = "Enter A value!";
        else if(bStr == "")
            message = "Enter B value!";
        else    
        {
            int res = Integer.parseInt(aStr)+Integer.parseInt(bStr);
            message = aStr+" + "+bStr+" = "+String.valueOf(res);        
        }
        Dialog.inform(message);
    }
}

Other option with FieldChangeListener is to declare and implement it inline. than you will not have to check from which field event is coming:

        mAddButtonField.setChangeListener(new FieldChangeListener() {
            public void fieldChanged(Field field, int context) {
                showAddResult();
            }
        });
Max Gontar
+1  A: 

or..

add(new ButtonField("Click Me")) {  
  protected boolean navigationClick(int status, int time) {  
    showAddResult();  
    return true;  
  }  
});  
bryanallott