JPanel to display large amount of text - java

I'm currently searching for a method to display an introduction for my program. Every part of the program has it's own instructions that are several lines long. At the end of each line there is \n\n for formatting.
It would be cool if the font size could adjust automatically to the panel size and if the text could be centered. I tried TextLayout and adding the text to a simple JLabel but none of this displays the text correctly.
Any suggestions on how to accomplish this task?

You can also use HTML formatting in the JLabel text. All you need to do is surround the text with <html> and </html>, set the font size with a <font> element, and replace every \n with <br>.
String formatted = text.replace("\n", "<br>");
formatted = "<html><font size='9'>" + formatted + "</font></html>";
JLabel label = new JLabel(formatted);
See How to Use HTML in Swing Components.

I agree with #Josh M, you should try using a JTextArea with a JScrollPane. Alternatively, if you do not expect too much GUI manipulation by the user, you could manually format the text using basic stuff like newlines ('\n') and tabs('\t').

You can give a columns count to your JTextField like this:
JTextField textField = new JTextField("I Have a Big Text and I want show it now!", 40);
40 is the column index which means the text has more columns for showing data in default now.
Another way you could do this is to use JTextArea

Related

Use line wrap in JTextArea that wraps the line to a specific position in JTextArea

I have a JTextArea that picks up text from another JTextArea and displays that text as seen in this image:
I want the JTextArea to wrap the line from where rahul is written as in previous image.
And below is the code from my smaller JTextArea from which the text is shown in the larger JTextArea.
SimpleDateFormat sdf=new SimpleDateFormat("HH:mm");
String str=MainFrame.un+" ("+sdf.format(new Date())+") :"+txtSend.getText();
DataServices.send(runm+":"+str); // for sending this to its socket
txtView.append("\n\n\t\t\t\t\t"+str);
txtSend.setText("");
txtSend.requestFocus(true);
i want it to start from where rahul is written just below that not from left edge of text area
This is not supported in a JTextArea. A JTextArea is used for displaying simple text.
You could use a JTextPane. It allows you to control attributes of the text and one of the attributes could be the left indent. So you can set the paragraph attributes for a single line to be indented by a specific number of pixels.
So instead of using tabs to indent the text you would just need to set the left indent when you add the line of text.
Note also that a JTextPane does not implement an append method so you would need to create your own by adding text directly to the Document using:
textPane.getDocument.insertString(...);
So the basic logic would be:
StyledDocument doc=(StyledDocument)textPane.getDocument();
doc.insertString(...);
SimpleAttributeSet attrs = new SimpleAttributeSet();
//StyleConstants.setFirstLineIndent(attrs, 50);
StyleConstants.setLeftIndent(attrs, 50);
doc.setParagraphAttributes(0,doc.getLength(),attrs, false);
This will change the indent of the line of text you just added to the text pane.

How can I make it so a JLabel only displays the first line of text?

Take a look at this picture:
This is a JLabel with a height that is not allowed to vary. However when there is too much text to fit in its given size it attempts to display both lines. I do not want this, how do I make it so that only the first line up to the "in new" is displayed?
Why not make it scrollable? This way you can maintain the preferred size, and at the same time display the info when it's needed. You just have to put the JLabel inside a JScrollPane:
JScrollPane scroller = new JScrollPane(yourJLabel,
JScrollPane.VERTICAL_SCROLLABAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLABAR_AS_NEEDED);
The solution was to not use html (ie, "<html>" inside of the string) for it was what was causing the lines to warp when too long. All bolding and monospacing had to be done without using html.

How to use HTML in Swing

I have a bit of an unusual problem:
I have a swing label that updates for "Used letters" in the game Hangman. I have it declared like this:
used = new JLabel(" Used: ");
But then i have another area in the code where i add onto it. Here:
used.setText(used.getText() + lUsed + " , ");
Now when the user enters letters, it updates the label and the letters are added, but if you enter enough, they push the rest of the contents of the frame out of view. The label expands the WEST side of my borderlayout so much that everything else get's pushed and then some times cut off the application window.
Is there a good way to use HTML to make it so that it word wraps the text and does not change the panel (what it's contained in) size?
GridLayout c = new GridLayout(rows,0);
westPanel = new JPanel(c);
westPanel.add(guessedPanel);
westPanel.add(usedPanel);
frame.getContentPane().add(westPanel, BorderLayout.WEST);
How it's laid out ^^
For a more general solution for those coming from Google, you can add HTML to Swing components very easily, as long as the content being added starts and
ends with the proper HTML tags.
For example, you may insert HTML text into a JLabel such that:
label.setText("<html> Text </html>");
You could color center it and underline the first letter like this:
label.setText("<html><center><u>T</u>ext</center></html>");
Here's a good tutorial on how to use HTML in your Swing components.
--
For your specific solution, you can simply use HTML when adding text to the label. Instead of using used.getText() you should store the text in a String somewhere (that does not enclose the opening and closing HTML tags), and update that String, in order to be able to effectively manage the opening and closing HTML tags. So it could go something like this
String text; // Earlier in the code
...
text += ("<br> " + lUsed);
used.setText("<html>" + text + "</html>")
Among other things, you could attempt setting a preferred or maximum size of the label so that it is not allowed to become to large. Also, you could make the label a text panel or text area of some kind instead, which would automatically support word wrapping, scrolling, and other features that you may want.
Here's a guide on how to use JTextAreas.
Specify a width in styles for the body tag of the HTML. See Text Wrap in JOptionPane for an example.

Set a string to bold in JTextArea?

I don't want to set the entire text area to bold but just a selected single line. How would go about doing that?
I suggest using a JTextPane instead as there are example solutions for it:
http://docs.oracle.com/javase/tutorial/uiswing/components/editorpane.html
http://www.java2s.com/Code/Java/Swing-JFC/JTextPaneStylesExample6.htm
There is no way to do it with JTextArea. You can achieve this with JEditorPane.
JEditorPane editorPane = new JEditorPane();
editorPane.setContentType("text/html");
editorPane.setText("<b>This text is bold</b>");
According to the documentation of JTextArea,
A JTextArea is a multi-line area that displays plain text.
plain text, in this sense, means every character is formated the same way. There is no way to format some characters differently than other characters.

Scroll through JLabel held in JScrollPane

I have a JScrollPane that holds a JLabel using the following code:
//Create TEXT LOG JPanel
textLogPane = new JScrollPane(logLabel);
textLogPane.setPreferredSize(textLogPaneDim);
//textLogPane.setOpaque(true);
textLogPane.setBorder(BorderFactory.createLineBorder(Color.BLACK));
textLogPane.getViewport().setBackground(Color.DARK_GRAY);
The JLabel, logLabel, is represented by a string with an HTML encoding using for carriage returns. I display certain images based on the contents of certain lines and I would like to be able to scroll the JScrollPane, textLogPane, to show that line whenever I am displaying that graphic. I know the contents of the line that I want to display but I can't seem to figure out how to get it to scroll down(or up) to the relevant line.
If need be I can change to something other than a JLabel as long as I can keep the HTML encoding and have it look just like multiple lines of text.
Sorry if this is a repeat I tried searching but couldn't find any results.
Thanks
You can do some custom maths and use scrollRectToVisible() in your viewport. I don't know how to compute the rect of a specific line in your JLabel. A better solution would be to stick your strings into a JList instead, perhaps with a custom renderer for the html, and use
list.ensureIndexIsVisible(list.getSelectedIndex());
You don't use "carriage returns" in HTML, you use "br" tags.
I would suggest you should probably be using a JTextPane for multiline text. I also find it easier to not use HTML, but instead to add strings with attributes. You can also insert icons into a JTextPane.
Read the section from the Swing tutorial on Using Text Components for a working example.

Categories

Resources