2012-01-05 60 views
1

我有一个Java Graphics的问题,我正在写一个程序,它读取一个文本文件并显示一些结果。Java抽取使用ArrayList中的数据的字符串

例如:

文本文件显示在屏幕上

print("Text",20,100) 
print("Hello",135,50) 

期望的结果2个字符串。 但我只拿最后一个。

我的代码示例:

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

//Add some data to the List 
StringsToDraw.add(new String[] {"Hello","20","35"}); 
StringsToDraw.add(new String[] {"World","100","100"}); 

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

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

我怎样才能改变它,以便它可以显示他们两人?

+0

你确定你没有绘制出你的图形的剪辑边界的界限吗? – rurouni 2012-01-05 11:07:35

回答

0

你的包围盒可能太小了。尝试一下,看看它是否适用于你:

public class Graphics2DTest extends JFrame { 
    private static final long serialVersionUID = 1L; 

    public static void main(String[] args) { 
     Graphics2DTest test = new Graphics2DTest(); 
     System.out.println(test); 
    } 

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

    public Graphics2DTest() { 
     super(); 

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

     setSize(400, 400); 
     setBackground(Color.YELLOW); 
     setForeground(Color.BLUE); 
     setVisible(true); 
    } 

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

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

您的代码有效。但是我忘了提及我使用了一个扩展了Canvas的类,它的大小是(480,272),最后一个Jpanel在另一个calss中显示画布。我试图将其更改为JFrame,我做了所有必要的更改,但重新使用的是白色的窗口。 (背景已在构造函数中设置为黄色) – nask00s 2012-01-05 13:10:27

+0

@ nask00s - 好的,您是否确认了画布的位置和大小?您可以通过将背景设置为其他UI组件中未使用的背景(例如酸橙绿)然后运行您的程序来完成此操作。如果之后的位置和大小关闭,那么你知道它的布局管理器问题。 – Perception 2012-01-05 14:17:18

相关问题