开发者

Learning Java, how to type text on canvas?

I'm reading a book by Eric Roberts - Art and science of java and it got an excersise that I can't figure out -

You have to make calendar, with GRect's, 7 by 6, that goes ok, the code part is easy, but also you have to type the numbers of the date on those rectangles, and it's kinda hard for me, there is nothing about it in the book.

I tried using GLabel thing, but here arises the problem that I need to work on those numbers, and it says "can't convert from int to string and vice versa". GLabel (string, posX, posY) - it is not accepting int as a parameter, only string, I even tried typecasting, still not working.

For example I want to make a loop

int currentDate = 1;

while (currentDate < 31) {

add(new Glabel(currentDate, 100, 100);

currentDate++;

This code is saying that no man, can't convert int to string. If i try changing currentDate to string, it works, but I got a problem with calculation, as I can't manipulate with number in string, it doesn't even allow to typecast it into int.

How can I fix it? Maybe there is another class 开发者_Python百科or method to type the text over those rectangles?

I know about println but it doen't have any x or y coordinates, so I can't work with it. And I think it's only for console programs.


Change your line

add(new Glabel(currentDate, 100, 100);

to

add(new Glabel(Integer.toString(currentDate), 100, 100);

toString() is a static method of the Integer class. You can use the method to convert any integer to a string.

One thing of note is that if you concatenate the integer to a String, the toString() method is automatically called. So this is another valid solution:

add(new Glabel("" + currentDate, 100, 100);


Try converting the integer to a string using this

String str = Integer.toString(inputInt);


A simple hack to ensure that it always works is:

int num = 10;
setText(num+"");//setText is any method that needs a string and you have an int
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜