这是我第一次在 stackoverflow 上发帖,所以请耐心等待。
我决定用 java 编写一个程序,读取包含“蓝色”、“绿色”、“红色”等文本的文件,然后根据它们在文本文件中的位置,在 JFrame 上绘制它们指示的颜色的正方形。我不确定这对某人是否有意义,但它突然出现在我的脑海中,我就像“嘿,我想我会尝试这个。”
基本上我想让我的 JFrame 第一行有 3 个方 block (红、蓝、绿)。然后我的下一行有 3 个方 block (蓝色、绿色、红色)。然后是最后一个(绿色、红色、蓝色)。
首先我的文本文件是这样的:
红蓝绿
蓝绿红
绿红蓝
现在我将发布代码。我不是 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
关于java - 需要帮助修复 Java 中读取文件并根据该文件生成图形的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10492203/