2

I have a JLabel, and as the JFrame window expands, the font size automatically changes. The text that is in the JLabel can either be abbreviated or put in full text like so:

Small and Large Window Exmaple

Because I am using Eclipse's "AbsoluteLayout" for Swing (frame.getContentPane().setLayout(null)), JLabels won't automatically resize to the size of the texts and are fixed values. Note that I do change those fixed values as the window changes size. I already have an algorithm for this.

Instead of doing a large calculation determining whether the window is large enough to display the un-abreviated text, I would like to know if there is a way to determine whether my text would appear like this:

Cut off JLabel text

If I could know that the text would be cut off (due to long text in a small JLabel), I could abbreviate the text, otherwise display it in full.

Is there any way to do what I'm asking while still using the AbsoluteLayout?

Note: It is necessary that I use AbsoluteLayout, so don't bother commenting about it even though it is typically regarded as bad practice.

Frakcool
  • 10,915
  • 9
  • 50
  • 89
P tray
  • 83
  • 1
  • 3
  • Possible duplicate of [Ideal method to truncate a string with ellipsis](https://stackoverflow.com/questions/3597550/ideal-method-to-truncate-a-string-with-ellipsis) – Frakcool May 10 '19 at 19:07
  • Possibly related: https://stackoverflow.com/questions/7971178/find-out-if-text-of-jlabel-exceeds-label-size – Frakcool May 10 '19 at 19:07
  • 1
    And avoid `null-layout`, you can even change the Layout Manager in Netbeans, so avoid it. [It's evil](https://www.leepoint.net/GUI/layouts/nulllayout.html) and [frowned uppon](https://stackoverflow.com/questions/6592468/why-is-it-frowned-upon-to-use-a-null-layout-in-swing), I bet I would get something like [this](https://stackoverflow.com/questions/42520492/jtable-not-showing-up-on-jframe-java/42521097#42521097) if I run your code in my computer, you **don't** want that to happen – Frakcool May 10 '19 at 19:11
  • Compare the size of the `JLabel` to the width of the text. There's no way to determine if the text fits whatever space without measuring how much the text takes. – Alexey Ivanov Mar 10 '23 at 14:20

1 Answers1

3

If I could know that the text would be cut off (due to long text in a small JLabel), I could abbreviate the text, otherwise display it in full.

Compare the width of getPreferredSize() and getSize().

camickr
  • 321,443
  • 19
  • 166
  • 288