开发者

java drawstring arraylist

If I am using the drawString(String, Int, Int) command in java. How can I store / call different graphics that have been stored in an ArrayList?

So, for example,

ArrayList<what type will this be???> list = new ArrayList;
int pos = 0;
for (int i = 0; i < list.size(); i++) {
    g.get(i).drawString("hello", 50, 50 + pos);
    pos开发者_StackOverflow中文版 += 20;
}


Did you mean:

list.get(i).drawString("hello", 50, 50 + pos);

If you want to store different objects/shapes in ArrayList<T>, the T has to be a superclass defining drawString(). Otherwise this code won't compile.


What is the problem doing that?

    List<Graphics2D> list = new ArrayList<Graphics2D>();
    int pos = 0;
    for (Graphics2D g : list) {
        g.drawString("hello", 50, 50 + pos);
        pos += 20;
    }

and you could better use for-each and define your list object using an interface List.


I used this for a program:

ArrayList<String[]> StringsToDraw = new ArrayList<String[]>(); 

StringsToDraw.add(new String[] {"Hello","20","35"}); 
StringsToDraw.add(new String[] {"World","100","100"}); 

@Override 
public void paint(Graphics g){
  for(String[] printMe : StringsToDraw){ 
    drawString(g, printMe[0], printMe[1], printMe[2]) 
  } 
} 

public void drawString(Graphics gr, String text, String xString, String yString){ 
    int x = Integer.parseInt(xString); 
    int y = Integer.parseInt(yString); 
    gr.drawString(text, x, y); 
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜