0

I have a JFrame as a top-level window of a Swing application used for editing files. I want to display a filename as editors usually do. My current code is a simple:

    frame.setTitle(appTitle + " - " + filePath)

Including a full path is desired, as I often open the file with the same filename from different directories. Sometimes however, when the window is narrow and the path long, the path will not fit into the space available and it is shown shortened, ending with ellipsis:

enter image description here

In such situation I would like to shorten the title myself. How can I check if the title I have provided is too long and would be shortened, so that I can shorten it myself instead, recursively if necessary, and dropping the information I consider least important (which is not the title end, containing the filename)?

Suma
  • 33,181
  • 16
  • 123
  • 191
  • Check https://stackoverflow.com/questions/258486/calculate-the-display-width-of-a-string-in-java might work for your problem as well –  Jan 06 '21 at 11:47
  • `g.getFontMetrics().stringWidth` can be a part of the solution. The rest is: how to find how much space has the title available (in pixels) and which font is used for the title. Not impossible, but I hoped perhaps someone has already solved this - the task does not seem that unusual. – Suma Jan 06 '21 at 11:51
  • I'm pretty sure the space used by the frame's icon and by the close/maximize/minimize button is a constant value (at least per os), so it can be measured and subtracted from the frame's width. –  Jan 06 '21 at 11:53
  • 1
    After some debugging I am afraid it will be more difficult than I expected. It seems it is not Swing who is responsible for the title rendering (and creating the ellipses), rather the OS. The title is a native property of the window. I will probably implement just some simple heuristic, displaying only a filename when the window width is below some limit. – Suma Jan 06 '21 at 12:24
  • Yes, probably just depend on the length of string. Hardly you can do anything here – HoRn Jan 06 '21 at 12:44
  • My suggestion is to add a JTextField for the directory path. That way the display is under your control. – Gilbert Le Blanc Jan 06 '21 at 18:55

0 Answers0