This is my first time posting on stackoverflow so bear with me.
I decided to write a program in java that reads a file that contains text such as "blue", "green", "red", and then draws squares on my JFrame that are of the color they indicate, and based on where they are in the text file. I'm not sure if that makes sense to someone, but it was something that just popped up into my head and I was like "Hey, i think i'll try this."
Basically I'd like to have my JFrame have the first row have 3 squares (red, blue, green). Then my next row have 3 squares (blue, green, red). Then last (green, red, blue).
first my text file is like this:
red blue green
blue green red
green red blue
and now i'll post the code. I'm not 100% sure what the error is, I've been running it in eclipse and it hasn't really told me anything useful that I know what to do with.
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);
}
}
I believe your main problem is that graphics is null. The next worse problem is that each time you call next() on the scanner, the previous string gets eaten. Instead use something like String color = row.next(), and use "color" in the rest of the loop.
You can get some ideas here: http://content.gpwiki.org/index.php/Java:Tutorials:Graphics
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.