Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Applet: read file and display properly

Status
Not open for further replies.

weasel669

Programmer
Joined
Apr 2, 2004
Messages
3
Location
US
I'm trying to read a file on the same system as the applet and display it in an applet window. my problem is the file which includes line breaks displays on one line. how can i fix this???

Code:
import java.applet.Applet;
import java.awt.Graphics;
import java.io.*;

public class Simple extends Applet {

    StringBuffer buffer;

    public void init() {
		buffer = new StringBuffer();
        readTextFromJar("datafile.txt");
    }

    public void readTextFromJar(String s) {
		String thisLine;
		try {
			InputStream is = getClass().getResourceAsStream(s);
      		BufferedReader br = new BufferedReader
         	(new InputStreamReader(is));
      		while ((thisLine = br.readLine()) != null) {  
         		System.out.println(thisLine);
         		buffer.append(thisLine);
         		repaint();
         	}
      	}
    	catch (Exception e) {
      		e.printStackTrace();
      	}
	}

    public void paint(Graphics g) {
        g.drawRect(0, 0, size().width - 1, size().height - 1);
        g.drawString(buffer.toString(), 5, 20);
    }
}

datafile.txt
Code:
line1
line2
line3
 
import java.applet.Applet;
import java.awt.Graphics;
import java.io.*;

public class Simple extends Applet {

StringBuffer buffer;
int lineCount=-1;
String line[] = new String[1000];
public void init() {
buffer = new StringBuffer();
readTextFromJar("datafile.txt");
}

public void readTextFromJar(String s) {
String thisLine;
try {
InputStream is = getClass().getResourceAsStream(s);
BufferedReader br = new BufferedReader
(new InputStreamReader(is));
while ((thisLine = br.readLine()) != null) {
System.out.println(thisLine);
line[++lineCount]=thisLine;
// repaint();
}
repaint();
}
catch (Exception e) {
e.printStackTrace();
}
}

public void paint(Graphics g)
{

g.drawRect(0, 0, size().width - 1, size().height - 1);

if (lineCount>0)
{
for (int i=0;i<=lineCount;i++)
{
g.drawString(line, 5, i*15+20);
}
}
}
}
 
Can you just not change this line :

buffer.append(thisLine);

to :

buffer.append(thisLine +"\n");

 
Thanks prosper, worked perfectly!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top