0

I am currently working on a project to mass-produce graphics such as you see below: enter image description here

The part I want to be able to swap out with any other word is is "<Table">. For aesthetic reasons, I want this text to always be dead-center in the rounded rectangle. I am using Graphics2D to achieve this; here is the code that generated the text:

        g2D.setColor(Color.WHITE);
        int fontSize = 55;
        int fontX = 410;
        int fontY = 75;
        g2D.setFont(new Font("Arial", Font.PLAIN, fontSize));
        g2D.drawString("<Table>", fontX, fontY);

I am going to create a method that generates fontSize, fontX, and fontY based on what would make it centered. If all characters were the same width, I would obviously not need help, but I am wondering how to handle very thin characters such as "i". I am not asking for anyone to solve the problem for me or give me the answer; in fact I would like to be able to figure it out myself. However, I do want some pointer on what to research/look up in order to solve this problem, as well as other considerations I didn't consider.

  • You're really going to want to spend some time reading through [Working with Text APIs](https://docs.oracle.com/javase/tutorial/2d/text/index.html). For [example](https://stackoverflow.com/questions/14284754/java-center-text-in-rectangle/14287270#14287270), [example](https://stackoverflow.com/questions/29247833/in-java-graphics2d-how-can-text-be-center-aligned-on-a-rectangle/29247946#29247946), [example](https://stackoverflow.com/questions/20794285/creating-a-string-inside-a-rectangle/20794440#20794440), – MadProgrammer Nov 16 '21 at 21:24
  • [example](https://stackoverflow.com/questions/18565066/centering-string-in-panel/18565132#18565132), [example](https://stackoverflow.com/questions/69308312/java-having-difficulty-centering-textlayouts-on-a-graphics2d-with-various-letter/69308607#69308607) – MadProgrammer Nov 16 '21 at 21:24
  • Now, having said that, I might consider a different approach, which might seem more complicated, but might make it easier to maintain. I might start with a custom layout manager (depending on the complexity of the layout) and have it control the layout of the "boxes", which would be custom panels (transparent, paint the borders all that) and then simply use a `JLabel` for the text. This allows the panel and label to control all the issues with calculating layout position of the text AND you get some extra support with limited HTML (if you want to do something fancy) – MadProgrammer Nov 16 '21 at 21:28

0 Answers0