// MatrixCanvas.java import java.awt.*; public class MatrixCanvas extends Canvas { private Matrix matrix; private int rows, cols, max, space = 20, rowHeight = 20, padding = 5, matrixWidth, matrixHeight; private int[][] A; private Font font = new Font("Monospaced", Font.PLAIN, 12); public MatrixCanvas(Matrix _matrix) { matrix = _matrix; rows = matrix.getRows(); cols = matrix.getCols(); A = matrix.getArray(); max = findMaxEntry(); matrixWidth = cols * max + space * (cols - 1) + 2 * padding; matrixHeight = rows * rowHeight; setSize(getPreferredSize()); } private int findMaxEntry() { int max = 0; for(int r = 0; r < rows; r++) for(int c = 0; c < cols; c++) { int temp = getFontMetrics(font).stringWidth(Integer.toString(A[r][c])); if (temp > max) max = temp; } return max; } public Dimension getPreferredSize() { return new Dimension(matrixWidth + 40, matrixHeight + 40); } public void paint(Graphics g) { int width = this.getSize().width, height = this.getSize().height; g.clearRect(0, 0, width, height); g.setFont(font); int strHeight = getFontMetrics(font).getHeight(), leftX = (width - matrixWidth) / 2, rightX = leftX + matrixWidth, upperY = (height - matrixHeight) / 2 - padding, lowerY = (height - matrixHeight) / 2 + rows * rowHeight - strHeight / 2 + rowHeight - strHeight + padding, capWidth; if (cols == 1) capWidth = 5; else capWidth = 7; for(int r = 0; r < rows; r++) { for(int c = 0; c < cols; c++) { String entryStr = Integer.toString(A[r][c]); int strWidth = getFontMetrics(font).stringWidth(entryStr); g.drawString(entryStr, leftX + (max + space) * c + max - strWidth + padding, (height - matrixHeight) / 2 + (r + 1) * rowHeight - strHeight / 2); } } g.drawLine(leftX, upperY, leftX, lowerY); g.drawLine(rightX, upperY, rightX, lowerY); g.drawLine(leftX, upperY, leftX + capWidth, upperY); g.drawLine(rightX, upperY, rightX - capWidth, upperY); g.drawLine(leftX, lowerY, leftX + capWidth, lowerY); g.drawLine(rightX, lowerY, rightX - capWidth, lowerY); } }