Java parsing long lines of text into multiple lines - java

I am new to programming and I would like some tips.
I have a program that reads from a text file using the the following method:
BufferedReader reader = new BufferedReader(new FileReader(file));
.....
This works but the problem is that some lines are long and I can't see all the text in the GUI. How should I tell Java to go to next line if length is equal to a certain amount?
Example text:
A week after Mozart died, his ghost was discovered trying to erase his music. When asked why, it said "I'm decomposing.
Instead of two lines, I want to parse it into four lines. Any help would be appreciated.

as per your comments, you are using JLabel for displaying the data.
to show multi-line text in JLabel just wrap your text in <html> tag like:
JLabel label = new JLabel("<html>your long text here ....</html>");
example:
String theReadLineFromTextFile = ....;
theReadLineFromTextFile = "<html>"+theReadLineFromTextFile+"</html>";
JLabel label = new JLabel(theReadLineFromTextFile);
//or
JLabel label = new JLabel();
label.setText(theReadLineFromTextFile);

If you can't do it in the gui, then some of the answers here will help: Wrap the string after a number of characters word-wise in Java

Related

Labels inside VerticalGroup do not keep to the left

As title says, I have a VerticalGroup that I store bunch of Labels in. Now, it does align ALL of them to the left, kind of. The problem is that labels that are shorter than the largest label will be centered around the middle of the largest label, like so:
Here is the relevant code:
private ScrollPane chatScrollPane;
private VerticalGroup chatGroup;
...
chatGroup = new VerticalGroup();
chatScrollPane = new ScrollPane(chatGroup, game.getSkin());
stage.addActor(chatScrollPane);
... in another method that adds messages ...
String message = "a message";
Label messageLabel = new Label(message, game.getSkin());
messageLabel.setAlignment(Align.left);
chatGroup.left();
chatGroup.addActor(messageLabel);
Now, what I'm asking is how can I have EVERY message, regardless of length, be on the left (like the Welcome message in screenshot)?
Thanks in advance.
I actually found the solution after quite a bit of fiddling. Turns out I need to do chatGroup.columnAlign(Align.left); to fix the problem. Thanks anyway!

JLabel with multiple lines and alignment to the right

I searched through many posts and figured out that JLabel supports HTML.
So I can do
JLabel search = new JLabel("<html>Search<br/> By:</html>");
to get multiple lines. Above code will result in
Search
By:
However, What I want is something like
Search
By:
Adding spaces before "By:" will work only when the window is not resizable(And very silly lol).
Can anyone tell me how to modify this code to make it work as I wanted?
Slightly simpler HTML than seen in #MadProgrammer's answer:
new JLabel("<html><body style='text-align: right'>Search<br>By:");
Non-breaking spaces ( ) are supported:
new JLabel("<html>Search<br/> By:</html>");
If you want to have real right-alignment, use individual right-aligned labels and combine them:
JLabel search = new JLabel("Search", SwingConstants.RIGHT);
JLabel by = new JLabel("By:", SwingConstants.RIGHT);
JPanel combined = new JPanel();
combined.setOpaque(false);
combined.setLayout(new GridLayout(2, 1));
combined.add(search);
combined.add(by);
or use a read-only JTextPane instead (with \n for line breaks):
JTextPane text = new JTextPane();
SimpleAttributeSet attributes = new SimpleAttributeSet();
StyleConstants.setAlignment(attributes, StyleConstants.ALIGN_RIGHT);
StyleConstants.setFontFamily(attributes, "Default");
text.setParagraphAttributes(attributes, true);
text.setEditable(false);
text.setOpaque(false);
text.setText("Search\nBy:");
There are a number of ways you might achieve this, one of the safer ways might be to use a <table> and aligning both cells to the right...
JLabel label = new JLabel(
"<html><table border='0' cellpadding='0' cellspacing='0'>" +
"<tr><td align='right'>Search</td></tr>" +
"<tr><td align='right'>By:</td></tr></table>"
);
This overcomes issues with differences between fonts and font rendering on different platforms

Including linebreak in StringBuilder

I'm having trouble trying to get a linebreak included in a Stringbuilder to appear in a JLabel.
I've found a couple of similar problems solved here, e.g. [here] Problems to linebreak with an int in JLabel and [here] How do I append a newline character for all lines except the last one? , along with a few others but none of them seem to work for me.
When printing to System.out, it works fine and I get a new line each time but when passed to a JLabel, everything appears as one line.
Here's the current version of the code, which has attempted to append a newline character, as well as including one in the main declaration. Neither has any effect when passed to the JLabel:
public void layoutCenter() {
JPanel central = new JPanel();
add(central, BorderLayout.CENTER);
JTabbedPane tabs = new JTabbedPane();
this.add(tabs);
// memory tab
StringBuilder mList = new StringBuilder();
memLocList = new Memory[MEM_LOCATIONS]; //Memory is a separate class
for (int i = 0; i < memLocList.length; i++) {
mList.append("\n");
memLocList[i] = null;
mList.append("Memory location: " + i + " " + memLocList[i] + "\n");
}
System.out.println(mList.toString());
JComponent memTab = makeTextPanel(mList.toString());
tabs.addTab("Memory", memTab);
}
protected JComponent makeTextPanel(String text) {
JPanel panel = new JPanel(false);
JLabel filler = new JLabel(text);
panel.add(filler);
return panel;
}
I've also tried using System.getProperty(line.separator) with similar results and can't think of anything else to try so thought I'd appeal for help here.
Thanks,
Robert.
-EDIT-
Thanks to mKorbel, changing the JLabel to a JTextPane solved it.
The two lines in question are:
JTextPane filler = new JTextPane();
filler.setText(text);
Thanks again to everyone.
JLabel isn't designated to held multilines document, there are two choices (by accepting newline or tab by default)
if document could not be decorated or styled somehow then to use JTextArea
in the case document could be decorated or styled somehow then to use JEditorPane or JTextPane
You're going to have to use <html> and <br> to get line breaks in a JLabel Swing component.
If you absolutely must use JLabel, then I suggest using one for each line.
You can make a JLabel have mulitple lines by wrapping the text in HTML tags and using br tags to add a new line.
If you news auto wrapping I suggest using a JTexrArea. You can make it uneditable and style it so it looks like a label.
You can look at this tutorial:
http://docs.oracle.com/javase/tutorial/uiswing/components/html.html
One of the example is using html to make it two lines for a JButton text. It should be very similar.

set background color from start to end char position

What would be an easy way to set the background color of all characters from some start to an end position in Java.
Eg:
red background from position D(4) to J(10)
String alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Many thanks in advance.
Edit:
Oh no, 2 '-'? Ok here is what I'm doing.
JTextArea textArea = new JTextArea("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
textArea.setFont(new Font("Courier", Font.PLAIN, 16));
//then I want red background from position D(4) to J(10)
please read Using Text Components and tons examples for that
look here for excelent workaround
Split the String into 3 separate Strings.
String a = alpha.substring(0,4);
String b = alpha.substring(4,11);
String c = alpha.substring(11);
Then display a,b, and c next to each other while only formatting b as desired.

Java newbie: Swing and displaying ASCII files

G'day all,
I have an application which needs to display an ASCII file of 15 lines in a Swing component that cannot be edited by the user.
Below is my code which reads the ASCII file byte by byte. My thanks to the helpful commenters who explained that a JTextArea.setEditable(false) would be appropriate in Swing.
However, my code merely displays a string of numbers, when I personally made the ASCII file to be something quite different. Does anyone know what I am doing wrong and how to get the ASCII characters themselves to display?
import java.io.*;
import javax.swing.*;
public class LoadMap extends JFrame {
public LoadMap() throws IOException {
FileInputStream fIn = new FileInputStream("map.srn");
BufferedReader rd = new BufferedReader(new InputStreamReader(fIn, "US-ASCII"));
String map = "";
JTextArea mapArea = new JTextArea(15, 50);
try {
int c;
while ((c = rd.read()) != -1) {
map= map + c;
}
} finally {
if (rd != null) {
rd.close();
}
}
mapArea.setText(map);
mapArea.setEditable(false);
add(mapArea);
pack();
setVisible(true);
}
}
You could construct a String inside the loop, and then put the string into JLabel when you've finished.
This makes me feel like Captain Obvious, but still: just load the entire text first, and then build the label using the desired text. Or, as other posters rightly suggest, use a JTextArea since its more well-suited for multiline content.
Use a JTextArea and call
setEditable(false);
to stop the user being able to edit the data
I've just read your code through and realise that's not a comprehensive enough answer. You can't do "+" on a label. What you need to do is read the text in first and store it somewhere, then call
setText(yourTextAsString);
on your text component on screen (for which I'd still use the JTextArea), and you need to add the text area to the frame, so your code would look something like:
public LoadMap() {
String data = // read your data
JTextArea textArea = new JTextArea();
textArea.setText(data);
textArea.setEditable(false);
setLayout(new GridLayout());
add(textArea);
pack();
setVisible(true);
}
I would suggest reading the Swing tutorial to get some more info on using Swing components
A JLabel will not display line breaks (unless you use HTML). So as the others wrote, use a text area.
However, there's another hidden problem with your code: you don't specify the file's encoding, which means the file contents may be garbled if it contains non-ASCII characters and its encoding does not match Java's platform default. To fix this, do not use FileReader. Instead, use a FileInputStream and wrap it in an InputStreamReader, specifying the encoding in its constructor.
Use a JTextArea and call setEditable(false).
https://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/text/JTextComponent.html#setEditable(boolean)
Here:
String map = "";
int c;
while ((c = rd.read()) != -1) {
map= map + c;
}
What you're doing it appending int's to the string.
You should cast them to char instead.
int c;
while ((c = rd.read()) != -1) {
map= map + ( char ) c;
}
You can see much better patterns in these questions.
How do I create a Java string from the contents of a file?
https://stackoverflow.com/questions/181634/simplest-efficient-ways-to-read-binary-and-ascii-files-to-string-or-similar-in-v/324792#324792 ( see java part )
You could use a JTextArea and set it to read only:
jtextarea.setEditable(false);

Categories

Resources