2012-01-05 58 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

相關問題