-2

I am going to develop j2me application. I want to know, how i can wrap text on canvas according to screen width size in J2ME.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Nilesh
  • 167
  • 3
  • 15
  • Please be more specific with your question. Do you want to implement a specific function for which you could give a signature? – einpoklum Apr 22 '19 at 16:14

2 Answers2

5

This is my code i used in my app it will wrapped lines vector and u can draw at any X point in canvas.

public static Vector wrapToLines(String text, Font f, int maxWidth) {
        Vector lines = new Vector ();
        boolean paragraphFormat = false;
        if (text == null) {
            return lines;
        }
        if (f.stringWidth(text) < maxWidth) {
            lines.add(text);
            return lines;
        } else {

            char chars[] = text.toCharArray();
            int len = chars.length;
            int count = 0;
            int charWidth = 0;
            int curLinePosStart = 0;
            while (count < len) {
                if ((charWidth += f.charWidth(chars[count])) > (maxWidth - 4) || count == len - 1) // wrap to next line
                {
                    if (count == len - 1) {
                        count++;
                    }
                    String line = new String(chars, curLinePosStart, count - curLinePosStart);
                    if (paragraphFormat) {
                        int lastSpacePosition = line.lastIndexOf(" ");
                        String l = new String(chars, curLinePosStart, (lastSpacePosition != -1) ? lastSpacePosition + 1 : (count == len - 1) ? count - curLinePosStart + 1 : count - curLinePosStart);
                        lines.add(l);
                        curLinePosStart = (lastSpacePosition != -1) ? lastSpacePosition + 1 : count;
                    } else {
                        lines.add(line);
                        curLinePosStart = count;
                    }
                    charWidth = 0;
                }
                count++;
            }
            return lines;

        }
    }

and while just run in for loop

int y=0;
int linespacing=4;
  for(int i=0;i<lines.size();i++)
  {
     g.drawString((String)lines.get(i),10,y,0);
     y+=(i!=lines.size()-1)?(font.getHeight()+linespacing):0;
   }

Enjoy :)

Ashok
  • 601
  • 8
  • 11
1

You need to calculate the width of the string to be drawn yourself and start a new line (split the string) each time you reach the max width of the canvas.

void paint(Graphics _g) {
  String t = "text to draw";
  int px_consumed = _g.getFont().substringWidth(t, 0, t.length())}
}
endevour
  • 708
  • 4
  • 12