Question

I have a Jpanel which for example is 500 width and 100 height. i have the formula to calculate the center of the screen vertically (y) and horizontally (x). Which i use to drawString(myText, x, y) but it writes the text above the bounds of the jpanel. Here is my paintComponent code i am using.

  protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D)g;
        String MenuString = Menu.get(MenuChannel);
        fontMetrics = g2d.getFontMetrics(realFont);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setBackground(Color.PINK);
        g2d.fillRect(0,0,getWidth(),getHeight());
        g2d.setColor(Color.WHITE);
        g2d.setFont(realFont);

        java.awt.geom.Rectangle2D rect = fontMetrics.getStringBounds(MenuString, g2d);
        int textHeight = (int)rect.getHeight();
        int textWidth = (int)rect.getWidth();
        int panelHeight = getHeight();
        int panelWidth = getWidth();
        int x = (panelWidth - textWidth) / 2;
        int y = (panelHeight - textHeight) / 2;
        System.out.println("tH:" + textHeight + "\ntW:" + textWidth + "\npH:" + panelHeight + "\npW:" + panelWidth);
        g2d.drawString(MenuString,x,y);
}
Was it helpful?

Solution

Yes - this is pain - drawString will draw your String using y as the bottom line (or base text line). If you want to center String in Rectangle you should just implement it using FontMetrics

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top