Java JLabel, break text to next line? - java

It's been awhile since I asked a question!
I'm developing an application in Java where JLabels are used. Anyway, as you may or may not be able to see from the picture below, the text that says Category Test gets cut off and ends up saying Categor... instead. Is there any way that I can "break" the text once it fills up the width of the label? Here is the image:
What I did
I used a JTextPane like so:
JTextPane text = new JTextPane();
SimpleAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setAlignment(attr, StyleConstants.ALIGN_CENTER);
pane.add(text, c);
Then I added my text, but thanks anyway!

JLabels can't do that by default. But JLabels have some support for html, so a JLabel with the text <html>First Line<br />Second Line</html> would show up on two lines.
If you want a component that can split the lines by itself, take a look at JTextArea.

As I recall, you need to use a JTextArea if you want textwrap. JLabel doesn't do it.

You can at StyledLabel component from JIDE Common Layer open source project at http://java.net/projects/jide-oss/.
The problem with html JLabel approach is it doesn't auto-wrap and about 20 to 40 times slower than a plain JLabel.
The problem with JTextArea or JTextPane approach is it has a weird size issue and is also 20 times slower.
StyledLabel extends JLabel. Automatically line wrapping is just one of the many features it adds. And the performance is as fast as a plain JLabel.
Hope it will help.

Related

How to set a line border around JTextArea?

I have a JTextArea in my panel, but it is hard to distinguish it from the background.
I tried setBound() but it doesn't really help.
Screenshot of my GUI
(The textarea is next to
the 'DESCRIPTION')
Is there any way to have a clear bound around it other than changing the colour of the background? Say having a line bound like what JTextField has(I put one next to 'EXPENSE' in my GUI).
Thanks for the guys in the comment area! I put the textarea into a JScrollpane. It does create a border:
using JScrollPane
Then I also added a line border to make it more clear.
des.setBorder(BorderFactory.createLineBorder(Color.BLACK));
Thanks again to Andrew Thompson, the suggestion about using GridBagLayout does make everything look much better.
Using GridBagLayout

Vertical JLabel Alignment

I was looking for a way to rotate JLabel vertically and I found that several posts related to this topic suggest to use Graphics2d. But, in this way, the size of my JLabel is inconsistent (widht & height inverted).
I found also that another user, here, suggested this code.
Actually, the code works, but there are no indications about how to align the text of the JLabel, and this is what i get:
Can anyone help with any of the two methods (controlling size in method one or 1 aligning text in method 2)?
Thank you very much in advance.
One way is to create an Icon of the text and rotate the Icon then add the Icon to the label. Then the size of the label will be calculated normally.
Check out the Rotated Icon class for an example of this approach. You will also need the TextIcon class.
These two classes may seem like extra work, but it is an example of how to create reusable classes to you don't do custom painting all the time.

JTextField enlarges in GridBagLayout

of course sorry for my bad English. I'm working on a window in which I have a panel and the panel within a form. The panel uses the distribution manager "GridBagLayout" I could properly distribute the components. My problem is that when filling a text field, type in the (JTextField) enlarges the field and does not retain its size. As you can see from the picture the more letters introduce the "Brand" field is becoming bigger. I'm working with NetBeans if someone happened or know what can be the problem Thanks in advance. Cheers
I am not sure about how to do this with a window editor like they have in NetBeans, but for GridBagLayout the power comes with how you configure your GridBagConstraints when you add another Component. If you want to keep every Component on a given row to keep their ratios fixed, then you need to define each of their GridBagConstraints.weightX fields to sum up to 1. So if you want something like:
|Label|TextField|Blank|
I would add Label with GridBagConstraints.weightX=0.3, TextField with GridBagConstraints.weightX=0.3, and a final "empty" Label("") as a buffer with GridBagConstraints.weightX=0.4. Total = 1.
There are of course tutorials available GridBag Tutorial

How to set jTextArea to have height that matches the size of a text it contains (to avoid scrollbars)

This problem looks trivial, but I can't find the solution.
When I create a form it contains a JTextArea. I want to put large constant text in it. If the text is say 1000 lines long, I want my JTextArea to be 1000 lines high (to be large enough to display the entire text without scrollbars). JTextArea is inside a panel which can have scrollbar so it is not a problem when it gets too large (there are two JTextArea in that panel.. something like in a diff tool). Does anybody knows how can I achieve this? Thanks.
The BorderLayout will handle the scrollbar out of the box if you simply put your JTextAreain a JScrollPane before you add it to your JPanel. FlowLayout, on the other hand, does not. It will not display the scroll bar unless, as #Xorty intimates, you call setPreferedSize() on your JScrollPane and give it the dimension that you would like.
You can also use something like this (limited width, height depending on text, useful when showing info messages):
public JTextArea createTextAreaFitToText(String message, Dimension minimalSize){
JTextArea aMessagePanel = new JTextArea();
aMessagePanel.setText(message);
/*for modelToView to work, the text area has to be sized. It doesn't matter if it's visible or not.*/
aMessagePanel.setPreferredSize(minimalSize);
aMessagePanel.setSize(minimalSize);
Rectangle r = aMessagePanel.modelToView(aMessagePanel.getDocument().getLength());
Dimension d = new Dimension(minimalSize.width, r.y + r.height);
aMessagePanel.setPreferredSize(d);
return aMessagePanel;
}
To increase or decrease the height of JTextArea. When a text is entered, call for getPreferredSize() of JTextArea- it'll give you the size needed to display the whole text.
After that use setPrefferedSize() of JScrollPane to set the size of JTextArea
Well, first of all : it's JTextArea not jTextArea.
Now - put JTextArea into JScrollPane. When a text is entered, call for getPreferedSize() of JScrollPane - it'll give you precise size needed to display whole text. Also, I never use other LayoutManager than 'Free Design' from NetBeans Swing builder - so I am not sure how other LayoutManagers will behave there.

How do I set the colour of a label (coloured text) in Java?

How do I set the color of the text of a label?
myLabel.setText("Text Color: Red");
myLabel.???
Can I have two seperate colors in one label?
For example here:
The "Text Color:" to be black and the "Red" to be red.
For single color foreground color
label.setForeground(Color.RED)
For multiple foreground colors in the same label:
(I would probably put two labels next to each other using a GridLayout or something, but here goes...)
You could use html in your label text as follows:
frame.add(new JLabel("<html>Text color: <font color='red'>red</font></html>"));
which produces:
You can set the color of a JLabel by altering the foreground category:
JLabel title = new JLabel("I love stackoverflow!", JLabel.CENTER);
title.setForeground(Color.white);
As far as I know, the simplest way to create the two-color label you want is to simply make two labels, and make sure they get placed next to each other in the proper order.
JLabel label = new JLabel ("Text Color: Red");
label.setForeground (Color.red);
this should work
object.setForeground(Color.green);
*any colour you wish
*object being declared earlier
One of the disadvantages of using HTML for labels is when you need to write a localizable program (which should work in several languages). You will have issues to change just the translatable text. Or you will have to put the whole HTML code into your translations which is very awkward, I would even say absurd :)
gui_en.properties:
title.text=<html>Text color: <font color='red'>red</font></html>
gui_fr.properties:
title.text=<html>Couleur du texte: <font color='red'>rouge</font></html>
gui_ru.properties:
title.text=<html>Цвет текста: <font color='red'>красная</font></html>
Just wanted to add on to what #aioobe mentioned above...
In that approach you use HTML to color code your text. Though this is one of the most frequently used ways to color code the label text, but is not the most efficient way to do it.... considering that fact that each label will lead to HTML being parsed, rendering, etc. If you have large UI forms to be displayed, every millisecond counts to give a good user experience.
You may want to go through the below and give it a try....
Jide OSS (located at https://jide-oss.dev.java.net/) is a professional open source library with a really good amount of Swing components ready to use. They have a much improved version of JLabel named StyledLabel. That component solves your problem perfectly... See if their open source licensing applies to your product or not.
This component is very easy to use. If you want to see a demo of their Swing Components you can run their WebStart demo located at www.jidesoft.com (http://www.jidesoft.com/products/1.4/jide_demo.jnlp). All of their offerings are demo'd... and best part is that the StyledLabel is compared with JLabel (HTML and without) in terms of speed! :-)
A screenshot of the perf test can be seen at (http://img267.imageshack.us/img267/9113/styledlabelperformance.png)
myLabel.setForeground(new java.awt.Color(255, 0, 0));
while numbers between brackets describe the combination of the Red,Green,Blue color values, the higher value produces a lighter color, the value can vary from 0 to 255.

Categories

Resources