[英]Need help fixing an error in Java with reading a file and generating graphics based on the file
這是我第一次在stackoverflow上發帖,所以請多多包涵。
我決定用Java編寫一個程序,該程序讀取包含諸如“ blue”,“ green”,“ red”之類的文本的文件,然后在JFrame上繪制它們所指示顏色的正方形,並根據它們所在的位置在文本文件中。 我不確定這是否對某人有意義,但這只是突然出現在我的腦海,我就像是“嘿,我想我會嘗試的。”
基本上,我希望JFrame的第一行具有3個正方形(紅色,藍色,綠色)。 然后我的下一行有3個正方形(藍色,綠色,紅色)。 然后最后(綠色,紅色,藍色)。
首先我的文本文件是這樣的:
紅色藍色綠色
藍綠色紅色
綠色紅色藍色
現在我將發布代碼。 我不是100%知道錯誤是什么,我已經在eclipse中運行了它,但它並沒有真正告訴我任何有用的有用信息。
import java.util.*;
import java.awt.*;
import java.io.File;
import javax.swing.*;
public class Test extends JFrame {
int currentY = 0;
int currentX = 0;
static Scanner squares;
private final static Graphics graphics = null;
Test(Graphics graphics) {
this.setVisible(true);
this.setSize(400, 400);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
while (squares.hasNextLine()) {
Scanner row = new Scanner(squares.nextLine());
while (row.hasNext()) {
System.out.println(row.next());
if (row.next().equals("green")) {
graphics.setColor(Color.GREEN);
}
else if (row.next().equals("red")) {
graphics.setColor(Color.RED);
}
else {
graphics.setColor(Color.BLUE);
}
graphics.fillRect(currentX, currentY, 20, 20);
currentX += 20;
}
currentY += 20;
}
}
public static void main(String[] args) throws Exception {
squares = new Scanner(new File ("C:/Test/data.txt"));
Test test = new Test(graphics);
}
}
我相信您的主要問題是圖形為空。 下一個更嚴重的問題是,每次您在掃描儀上調用next()時,前一個字符串都會被吃掉。 而是使用類似String color = row.next()的名稱,並在循環的其余部分使用“ color”。
您可以在此處獲得一些想法: http : //content.gpwiki.org/index.php/Java : Tutorials : Graphics
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.