FontMetrics fm = label.getFontMetrics(font); // font is the font you use
int strWidth = fm.stringWidth("String"); // This can get the length of the string (pixels), the height of the string is generally the size of the font
int width = 200; // length of rectangle
int high = 50; // the height of the rectangle
drawString("String", (width-strWidth) / 2, (high-font.getSize()) / 2 + font.getSize());
drawString("String", X, Y); can solve the centering problem
Use "..." for the excess part ==> If the figure is exceeded, it is not displayed, only the word exceeds...
It is recommended to draw on a JPanel add(JPanel, BorderLayout.center)