javajava-memidpmidlet

Need help to track ball position in JAVA


I am creating a bouncing ball in Netbeans using J2ME Loader.

I have done the bouncing ball parts but struggling to track the ball position.

I have searched online but not so much information there. Anyone can advice?

Here is the code:

package mobileapplication8;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.midlet.*;


public class Midlet extends MIDlet {
    Display d;
        MyCanvas m;
     Timer t;
    MyTask mt;
    int x=10,y=10;
    int xiner=1,yiner=1;
    Command start, stop;
     Command c;


    public void startApp() {
          d=Display.getDisplay(this);
       m= new MyCanvas();
       d.setCurrent(m);

    }

    class MyTask extends TimerTask
    {
        public void run()
        {
            m.repaint();
           
        }
    }
    class MyCanvas  extends Canvas implements CommandListener
      
    {
        MyCanvas()
        { start=new Command("start", Command.SCREEN,1);
        addCommand(start);
   stop=new Command("stop", Command.SCREEN,2);
        addCommand(stop);
       setCommandListener(this);}
     public void  paint(Graphics g)
        {  g.setColor(255,255,255);
              g.fillRect(0,0,getWidth(),getHeight());
              g.setColor(255,0,0);
                  
              x+=20*xiner;
              y+=50*yiner;
              if(x>getWidth()-20 || x<0 )
              { xiner*=-1;
                  }
              if(y>getHeight()-50||y<0)
              {yiner*=-1;
             
              }
            g.fillArc(x,y, 20,20,0,360);
       
    }
        public void commandAction(Command c, Displayable d) {
          //  throw new UnsupportedOperationException("Not supported yet.");
      if(c==start)
     {
      t=new Timer();
      mt=new MyTask();
      t.schedule(mt,1000,500);
           }
     else if(c==stop)
     {
          t.cancel();
          mt.cancel();
     }   }
    }
   
    public void pauseApp() {
    }
   
    public void destroyApp(boolean unconditional) {
    }

}

As you can see the output is only showing the ball bouncing like this image below

enter image description here

This is the output that I wanted which is to get the ball position every time it moves, but failed to achieve it, see below image

enter image description here


Solution

  • Add below code in paint method

    String s = "(" + x + "," + y + ")";
    g.drawString(s, 0, 0, Graphics.TOP | Graphics.LEFT);
    

    https://docs.oracle.com/javame/config/cldc/ref-impl/midp2.0/jsr118/javax/microedition/lcdui/Graphics.html#drawString(java.lang.String,%20int,%20int,%20int)