suggestion on how to read a large file to jtextarea - java

I want to read large file like 10-15k lines to jtextarea.
Beside that, I also have to add every line to List and to highlight some specific lines in jtextarea.
What I tried for now is, I pass file into FileReader into BufferedReader. Inside my SwingWorker, in doBackground method I call:
while ((line = br.readLine()) != null) {
textArea.append(line);
textArea.append(System.getProperty("line.separator"));
list.add(line);
highlightLine(lineNumber);
}
When I run the program, and I choose file and open read process, it instantly loads up to 700 lines, then program slows down and loads like 10 lines per second.
Another idea I have is to, read a whole file with JTextComponent read method (which seems to setText faster then append every line), and then, read again whole file or iterate through every line in jtextarea and add that line to List and also highlight, which I think is not very efficient. What do you suggest me?

I want to read large file like 10-15k lines to jtextarea
Use the read(...) method of the JTextArea class to read the entire file directly into the text area.
I also have to add every line to List
Why do you need two copies of the text? If you need a line of data you can get the text from the text area:
int start = textArea.getLineStartOffset(...);
int end = textArea.getLineEndOffset(...);
String text = textArea.getDocument().getText(...);
to highlight some specific lines
Use a Highlighter to highlight the lines after they have been loaded into the text area.
Highlighter highlighter = textArea.getHighlighter();
highlighter.addHighlight(...);
Again you can get the offsets of the line using code from above.

Use the Document interface. it is the model that holds the data of the view-component that is JTextArea. You can get it from JTextArea with getDocument or you can use one of the classes that already implement Document: AbstractDocument, DefaultStyledDocument, HTMLDocument, PlainDocument. Then add your Document of choice to JTextArea with setDocument.
You can use insertString(int offset, String str, AttributeSet a) to add content to the Document. It also supports several listeners and you could consider a using render(Runnable r) to style it the document.

I haven't tried this but I would suggest putting all the file contents into a String, then use the setText(String text) method to set the text of the JTextArea all at once.

Related

How do you read text from a JTextArea one line at a time?

How do you read text from a JTextArea one line at a time?
I can only find the JTextArea.getText(<no parameters>) function in the docs, but nothing about reading based on line number. I can get the indices of the start and the end of a given line, and the total number of lines, but I don't know how to extract the data one line at a time.
I'm not understanding the question.
Why would you read an entire file into a JTextArea and then read the text in the text area and parse the data?
The point of my answer was that you:
Read the CSV file line by line
You then parse each line to get the 3 columns of data you need
If you really need the entire data in the text file, then you just use the append(...) method of the JTextArea to add each line of data as you read it.
The only output of a JTextArea is with JTextArea.getText()
If you really want to get the data from the text area then read the JTextArea API. The following methods will help you out:
getText(...) method where you specify the "offset" and "length" parameters, so you can get a line of text
getLines() for the number of lines of text in the text area
getLineStartOffset(...) and getLineEndOffset(...)
So now you can create a loop and get the text for each individual line.

Opening a file into a JLabel

I want to create a program which allows the user to input a file name and then it shows everything written in the file in a JLabel, I have managed to find/create code which allows the user to input the name of the file and then show the contents of the file in the console but I couldn't find a way to show everything from the text file in a JLabel.
Is there a way to do this? As some people have told me that it is not possible to do this.
Yes...it is possible but as already mentioned you would be far better off using the JTextArea or similar component instead and most likely save yourself some grief.
Although a JLabel is basically designed for a single string line of text it does allow for that text to be wrapped within HTML tags therefore allowing for basic HTML/CSS to format that same text. The trick then is to read each line of a desired text file into a single string variable formatting that string as you append each line read and, by formatting, I mean adding:
A Title;
Line Breaks;
Indenting;
Left Marginal Padding;
Line Wrapping;
Bold, Italics, Underlining;
Fonts, Font Style, Font Sizes, and even Font Colors;
Text alignments like Left, Center, Right, and Justify;
etc, etc, etc.
A JLabel doesn't recognize the usual line breaks you're already familiar with like "\n" or "\r\n" or even System.lineSeparator();. It will however deal with the HTML Line Break tag of <br> but only if the text being applied to the JLabel is wrapped within HTML. Here is an example of a two line JLabel text:
String txt = "<html>This is line one.<br>This is line two.</html>";
jLabel1.setText(txt);
Ultimately your JLabel would look something like this:
Notice in the code line above that the String text starts with <html> and ends with </html>. Any text between these two tags is considered to be wrapped in HTML. You will also notice the <br> tag within the string which forces the Line Break so as to create two lines.
A JLabel is very limited to what it can do and without HTML it can't really do anything bullet listed above and display a text file within a JLabel like this:
You will of course notice the Scrollbar in the above image. Yet another problem with the JLabel, it won't display Scrollbars if needed. You need to place the JLabel into a JScrollPane to have this feature since there may very well be files that are going to exceed the boundaries of your JLabel so you need to also consider this. Simple enough, not the end of the world.
The method provided below will read in the supplied text file and display it within the supplied JLabel. It will automatically wrap everything into HTML, Provide the title, Left pad all the text by 10 pixels, Line Wrap the text, handle Line Breaks, and take care of basic Indentation:
public void displayFileInJLabel(JLabel label, String filePath) {
try {
// Try With Resources (will auto close the reader).
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
/* We use StringBuilder to build our HTML Wrapped
string to display within the JLabel. */
StringBuilder sb = new StringBuilder();
// Get the width of our supplied JLabel
int w = label.getWidth();
/* Calculations for determininfg Line Wrap.
The (w / 4) is a modifiable offset. */
String width = String.valueOf((w - (w / 4)));
/* Deal with Line Wrap (JLabels don't do this) and
set up Left Padding. */
sb.append("<html><body style='width: ").append(width).append("px; padding:10px;'>");
/* Apply the Title Center of JLabel, Blue Color Text,
and Bold Font Style.The size of the text is determined
by the <h1> and </h1> tags. */
sb.append("<center><h1><font color=blue><b>").append(filePath).append("</b></font></h1></center><br>");
// Read in File Lines one at a time.
String line;
while((line = reader.readLine()) != null) {
/* Deal with multiple whitespaces (basic indenting etc) since HTML
doesn't deal well with more than a single whitespace. */
line = line.replaceAll("\\s{4}", " ");
/* Deal with line breaks. JLabels won't deal with them since
it is designed for a single line of text. We therefore
apply the HTML Line Break tag (<br>)at the end of each
text file line to take care of this business. */
line+= "<br>";
sb.append(line);
}
// Apply the closing tags to finish our HTML Wrapping.
sb.append("</body></html>");
/* Set the formated HTML text to the JLabel */
label.setText(sb.toString());
}
}
catch (IOException ex) {
Logger.getLogger("displayFileInJLabel() Method").log(Level.SEVERE, null, ex);
}
}
If you remove all the commenting then it really isn't that much code but there is yet more to do. To build the form sample displayed above
Create a new JFrame Form;
Set it's DefaultCloseOperation property to DISPOSE;
Set it's AlwaysOnTop property to true;
before the Form is displayed set it's SetLocationRelativeTo
property to null;
Place a JScrollPane into the JFrame form. Have it take up the
entire size of Form;
Place a JLabel into the JScrollPane. Have it take up the entire size
of the JScrollPane;
Set the JLabel's Background color to White;
Set the JLabel's Opaque property to true;
Set the JLabel's HorizontalAlignment to LEFT;
Set the JLabel's VerticalAlighnment to TOP;
Make sure the JLabel Text property is empty (nothing);
Copy and Paste the displayFileInJLabel() method into an
accessible place. Within your JFrame Form Class will do if you like.
Place a call to the displayFileInJLabel() method within the
JFrame's ComponentResized event, something like this:
displayFileInJLabel(jLabel1, "C:\\MyFiles\\LoremIpsum.txt");
Better to have a class member variable hold the file path to view rather than hard coding it then fill this member variable in the Form's Class Constructor that would have a String Type parameter.
It's all a matter of what you really want to do. Using a JTextArea is still a better idea.

How to read from a file and in the file display only the lines starting with integers

I want to read from a file and display it in a combo box and it must show only lines starting with numbers
The txt
11 Fufu high school
Brie
Enjoy
Yoyo
12 TLT high school
High
Right
Pupu
So from your description, you need a way to read characters from a file, filter them out such that lines which are showing numbers are showing, and then display this to a combo box.
To begin, you will need a class called BufferedReader. An example of the use can be seen below
String filename = "yourFileName"
BufferedReader bw = new BufferedReader(new FileReader(filename))
String line = bw.read()
Once the BufferedReader is created, you can read the lines of text from file and now the only thing left to do before pushing these strings to the combobox is to filter out the lines you do not want. Since we do not know the formatting of the file you have, the next best thing is to point you towards the String class api which can be used to filter the string however you need it to be done
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Once the formatting has been done, you can add an item to the combobox (assuming you are using a JComboBox from swing) using the method addItem()

convert a method to work with gui

I've got a huge method that prints multiple lines, numbers, characters and uses system.out and multiple data types, it works. But I'd like to use it in a jframe. I tried converting every system.out statement to a jtextArea.setText(), and did casting for non string types but nothing comes out when I run it.
Is it possible? what is the right way of doing that.
jtextarea right for my method.
If you wish to append text to a JTextArea, use the append method. Right now your code is using setText, which does just that: sets the text of the JTextArea, removing all previous text in the process (and in this way your code seems to almost guarantee that the JTextArea either contain no text, or contain a single new line character).
try jTextField if its only gonna output.
Try jTextField.append if the user will write stuff on the text.

How can i display multiple texts in text container of a wizard

I would like to display multiple texts in a text wizard container. I have used the setText method but it displays only the last text. Please can someone gives me a solution
As its name suggests Text.setText sets the text displayed in the control and discards any previous text. So you need to construct a string containing all the data you want to show in the control and call setText with this. You could use a StringBuilder for this, something like:
StringBuilder buff = new StringBuilder();
for (Object element : al)
{
buff.append(element).append("\n");
}
text.setText(buff.toString());
You will need to create the control specifying the SWT.MULTI style and make sure it is sized to show multiple lines.

Categories

Resources