Jump to content

Paint Grid Snippet V2


Recommended Posts

Posted (edited)

V2: Now splits up the rows into equal sections based on the corresponding row in String[][] data.

private void drawGrid(Graphics2D g, String[][] data, int cellWidth, int cellHeight) {
    g.setFont(font);
    g.setColor(GRID_BG); //Background Color of Grid
    int maxNumCols = 0;
    for (String[] row : data) {
        maxNumCols = Math.max(maxNumCols, row.length);
    }
    if (gridCanvas == null)
        gridCanvas = new Rectangle(cellWidth * maxNumCols, cellHeight * data.length);
    g.fill(gridCanvas);
    g.setColor(Color.WHITE); // Color of Text and Grid lines
    g.draw(gridCanvas);


    // draw the horizontal lines
    for (int i = 0; i <= data.length; i++) {
        int y = i * cellHeight;
        g.drawLine(0, y, cellWidth * maxNumCols, y);
    }

    for (int row = 0; row < data.length; row++) {
        int numElementsInRow = data[row].length;

        for (int col = 0; col < numElementsInRow; col++) {
            // draw the strings in the right positions
            int textX = col * (gridCanvas.width / numElementsInRow) + (gridCanvas.width / (numElementsInRow * 2) - g.getFontMetrics().stringWidth(data[row][col]) / 2);
            int textY = row * (gridCanvas.height / data.length) + (gridCanvas.height / (data.length * 2)) - g.getFontMetrics(font).getHeight() / 2 + g.getFontMetrics().getAscent();
            g.drawString(data[row][col], textX, textY);

            // draw the vertical lines. Dividing each row into {numElementsInRow} sections
            for (int i = 0; i < numElementsInRow - 1; i++) {
                int x = col * (gridCanvas.width / numElementsInRow);
                g.drawLine(x, row * cellHeight, x, row * cellHeight + cellHeight);
            }
        }
    }
}

Designed to be universal for all scripts to quickly show data. Functional Examples...

https://github.com/YifanLi5/Mark-And-Chop/blob/master/src/Paint/ScriptPaint.java

https://github.com/YifanLi5/OttoGrottoFisher/blob/OttoGrottoFisher/src/Paint/ScriptPaint.java

 

Preview:

https://imgur.com/a/wx8K77D

Edited by yfoo
  • Like 1
  • yfoo changed the title to Paint Grid Snippet V2

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...