5

I have included an image in my JavaFX TextField by following this post, but now my problem is that the text can overflow to cover up the image, like this:

Textfield text overlaps on image

What I want to do is, instead of the TextField moving & cutting off the text when I get to the edge of the TextField, it should start cutting off visible text when I get to the left edge of the image. How can I do this?

Zephyr
  • 9,885
  • 4
  • 28
  • 63
sacic
  • 53
  • 5

1 Answers1

7

Probably the simplest way to do this is to set the padding on the right side of your TextField to account for the image:

-fx-padding: 4px 25px 4px 7px;

This will keep the default padding for the top, bottom, and left, while updating the right value. The 25px here may need to be adjusted based on your image, but here's my example:

textField.setStyle(
        "-fx-background-image: url('resources/play.png');" +
        "-fx-background-repeat: no-repeat;" +
        "-fx-background-position: right center;" +
        "-fx-padding: 4px 25px 4px 7px;"
);

screenshot

Zephyr
  • 9,885
  • 4
  • 28
  • 63
  • 1
    Didn't even think about that. Thanks so much! That works. – sacic Aug 22 '19 at 19:14
  • How do you make sure only the right side padding is affected? – trilogy Aug 22 '19 at 19:32
  • @trilogy The `-fx-padding:` attribute takes 4 values. I keep all of them at the default 5px and only update the second one, which corresponds to the right side. I believe they are, in order, `top`, `right`, `bottom`, `left`. – Zephyr Aug 22 '19 at 19:37
  • @Zephyr oh is 5px always the default? – trilogy Aug 22 '19 at 19:38
  • @trilogy - No, I hadn't looked up the actual original values but just went with what looked close. Per `modena.css`, a `TextField` has the following default padding: `0.333333em 0.583em 0.333333em 0.583em` or `4 7 4 7` – Zephyr Aug 22 '19 at 19:44
  • I think `em` is a multiplier to the default font size. Therefore, I'm wondering if leaving the original values in `em`'s and then making the right padding based on how large the image is, rightly in pixels: for example: `-fx-padding: 0.333333em 25px 0.333333em 0.583em;` Would that be best? Too bad JavaFX doesn't have `-fx-padding-right` – trilogy Aug 22 '19 at 19:59
  • That would be fine as well, @trilogy. – Zephyr Aug 22 '19 at 20:02