0

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 += 20;
}
Ricco
  • 775
  • 5
  • 11
  • 19

3 Answers3

0

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.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • If i is lets say an integer and I iterate from 0 - 10 and create 10 strings "hello" in different positions, if I then call list.get(2).drawString("hello", 100, 100); Will that only move one of the strings that was referenced at list position 2? – Ricco Aug 10 '11 at 06:59
0

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); 
}
nask00s
  • 97
  • 1
  • 8
0

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.

jenaiz
  • 547
  • 2
  • 15