javagraphicsgraphics2djlayeredpane

Why do these chars get cut of on the bottom?


I'm building a chess board, I'm going to layer two JPanels on top of each other , the bottom one "Sideline" should display the grid code, while the top one is gong to contain the actual game board.

However, the letters are cut off at the bottom and I'm wondering what's going on here?

enter image description here

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;

public class Main {

    public static void main(String[] args) {

        JFrame frame = new JFrame();
        JLayeredPane lPane = new JLayeredPane();
        Sideline sl = new Sideline();

        frame.setTitle("Chess MF");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLocation(350, 200);

        // setup Center Panel
        frame.getContentPane().add(lPane, BorderLayout.CENTER);
        lPane.setPreferredSize(new Dimension(540, 540));

        sl.setBounds(20, 20, sl.getWholeSize(), sl.getWholeSize());

        lPane.add(sl, Integer.valueOf(0));

        frame.pack();
        frame.setVisible(true);

    }
}

class Sideline extends JPanel {

    private int sidelineSize = 20;
    private int wholeSize = 500;
    private int fieldSize = 60;
    Font font = new Font("Arial", Font.BOLD, 20);

    @Override
    public void paintComponent(Graphics g) {

        Graphics2D g2 = (Graphics2D) g;
        RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING,    RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setRenderingHints(rh);
        g2.setFont(font);

        int row, col;
        int x, y;
        String rowName = "12345678";
        String colName = "abcdefgh";

        for (row = 0; row < 8; row++) {
            x = 0;
            y = row * fieldSize + sidelineSize + g.getFont().getSize() / 2;
            g.drawString(String.valueOf(rowName.charAt(row)), x, y);
        }
        for (col = 0; col < 8; col++) {
            x = col * fieldSize + sidelineSize + g.getFont().getSize();
            y = 8 * fieldSize + sidelineSize;
            g.drawString(String.valueOf(colName.charAt(col)), x, y);
        }
    }

    public int getSidelineSize() {
        return sidelineSize;
    }

    public int getWholeSize() {
        return wholeSize;
    }

}


Solution

  • Try

            FontMetrics fm = g.getFontMetrics();
            for (col = 0; col < 8; col++) {
                x = col * fieldSize + sidelineSize + g.getFont().getSize();
                y = 8 * fieldSize + sidelineSize - fm.getMaxDescent();
                g.drawString(String.valueOf(colName.charAt(col)), x, y);
            }