Set width of a JLabel and add a tooltip when hovering
18,897
Solution 1
The size of your JLabel
is determined by the LayoutManager
of the parent container. Consult the tutorial for more information.
Note that the JLabel
has already the behavior you are looking for
- When the text is too long, the text which is cut-off will be replaced by "..." . So in your example, the "Verylonglabel" would be replaced by e.g. "Verylo..."
- You can use the
setToolTipText
method to specify the tooltip, which will be shown when hovering over theJLabel
Solution 2
This is what you need:
JLabel label = new JLabel("Verylonglabel");
// Create tool tip.
label.setToolTipText(label2.getText());
// Set the size of the label
label.setPreferredSize(new Dimension(80,40));// Width, Height
Related videos on Youtube
Comments
-
Goatcat almost 2 years
I have a
JLabel
with unknown content and I have two things I want to do:- I want to set a maximum or perhaps even static width of the label. And if the text is larger than the label it would somply shorten it, like this:
Verylonglabel
becomes
Veryl
Is it a bad idea to use static width on components in a gui? If that is the case, what is the alternative? Please give me advice!
- When you hover over the label I want a tooltip with the full length string to appear. So in our case, if i hover over the label that says "Veryl", a tooltip displaying "Verylonglabel" would appear. However, it should display a tooltip with the full length string even if it was not shortened.
Help with either of these is greatly appreciated.
So far I've just messed around a bit and tried things like this without sucess. It doesn't seem to care about the size at all.
JLabel label = new JLabel("Verylonglabel"); label.setSize(15, 5);
Best regards, Goatcat
-
Goatcat almost 11 yearsThank you for you answer, i have a question though: You say "1. When the text is too long, ..", but what decides when it is too long? Where do i set this value? I am now using MigLayout btw.
-
Goatcat almost 11 yearsSome people say that you should avoid
.setPreferredSize()
. What do you have to say on the subject? When is it safe to use, and when should it be avoided? -
Robin almost 11 years@Goatcat your
LayoutManager
decides this. YourJLabel
decides what its preferred size is based on the text. However, it depends on theLayoutManager
whether it respects that preferred size or not -
Gilbert Le Blanc almost 11 yearsYou should generally avoid using setPreferredSize because your GUI component won't change size when the window changes size, like when the user maximizes the window.
-
Goatcat almost 11 years@Robin and Gilbert Le Blanc, thank you both very much for your help!