1 Replies - 1337 Views - Last Post: 09 October 2012 - 12:43 PM Rate Topic: -----

#1 alpha_x  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 55
  • Joined: 03-May 11

Reading a text file and printing to g2d.drawString()

Posted 09 October 2012 - 12:35 PM

Hey all, I am trying to read a file in and then store it in a string. I then want to draw the string to the screen using g2d.drawString but I want to draw a new String every time the charachter '#' at a lower height to simulate '\n'.

Here is my code where I retrieve the lines from the text file:

	public String loadFile(String fileName) throws IOException {
		// get file length
		String ret = "";
		FileReader in = new FileReader(fileName);
		BufferedReader inF = new BufferedReader(in);
		String line = inF.readLine();
		ret += line;
		while (line != null) {
			line = inF.readLine();
			ret += line;

		return ret;


And here is my code that is meant to draw the lines from the file to the screen:

if (helpString != null) {
			int difference = 20;
			int y = 50;
			for (String helpStringData : helpString.split("#"))
				g2d.drawString(helpStringData, 40, y += difference);

So if I click a JButton called help, it will then load the file and store it in helpString like so helpString = loadFile("help.txt");

If for example help.txt contains:

HELP#This is the help data

Then I call the method that draws it to the screen using the second code snippet above. It works however it draws the following:

This is the help data

I am guessing this is because there is not another # and so the helpStringData contains a null however how would I go about stopping this from happening?

I tried

if (helpStringData != null) {
	if (helpStringData != null) {
				g2d.drawString(helpStringData, 40, y += difference);

And I still get the same problem... Any help is appreciated, thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: Reading a text file and printing to g2d.drawString()

#2 g00se  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3225
  • View blog
  • Posts: 14,236
  • Joined: 20-September 08

Re: Reading a text file and printing to g2d.drawString()

Posted 09 October 2012 - 12:43 PM

Wouldn't it be a whole lot easier to use a text component? ;)

If you're determined then just use a Scanner on the file:

while(scanner.hasNextLine()) {
	g2d.drawString(scanner, 40, y);
	y += offset;

This post has been edited by g00se: 09 October 2012 - 12:55 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1