[英]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.