Goatcat
Goatcat

Reputation: 1143

Set width of a JLabel and add a tooltip when hovering

I have a JLabel with unknown content and I have two things I want to do:

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!

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

Upvotes: 3

Views: 21181

Answers (3)

Josh Britton
Josh Britton

Reputation: 83

setMaximumSize will only be effective if the LayoutManager you use honors components' desired/max sizes. You may want to check out BoxLayout as a LayoutManager. Unlike several other Swing LayoutManagers, BoxLayout honors the size settings of its components.

This still leaves you the question of what size to set as the maximum size. The width will be whatever you are targeting as your fixed value, but the height should be big enough for whatever font is being used. Here is the code I would use to make the height flexible but the width fixed to 50 pixels:

label.setMaximumSize(new Dimension(10000, 50));

Finally, the tooltip will show the full label text with a line like:

label.setToolTipText(labelText);

Upvotes: 0

ColinWa
ColinWa

Reputation: 999

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

Upvotes: 3

Robin
Robin

Reputation: 36601

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

  1. 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..."
  2. You can use the setToolTipText method to specify the tooltip, which will be shown when hovering over the JLabel

Upvotes: 5

Related Questions