/** * A Swing representation of a TreeMyopicCol position. * @author Kyle Burke <paithanq@gmail.com> */ import java.awt.*; import javax.swing.*; public class TreeMyopicColPanel extends JPanel { //underlying game private TreeMyopicCol position; /** * Class constructor. * * @param position The TreeMyopicCol game that this will display. */ public TreeMyopicColPanel(TreeMyopicCol position) { this.position = position; } //@override public void paintComponent(Graphics g) { int height = this.getHeight(); int width = this.getWidth(); g.clearRect(0, 0, width, height); PureBinaryTree<Integer> tree = this.position.getTree(); int treeHeight = tree.getHeight(); this.paintSubtree(g, tree, treeHeight, height-5, width, 5, 0); } //paints a subtree of the tree in a portion of the overall canvas // Graphics g does the actual drawing (like a paint brush) // tree is the subtree we are going to be drawing // treeHeight describes the number of levels in the WHOLE tree even with and including this level. // height is the height of the area we're going to draw this tree in (in pixels) // width is the width of the area we're going to draw this tree in (in pixels) // xOffset is the (left-to-right) pixel index of the upper-left-hand corner of the box in the canvas we're going to draw this tree in // yOffset is the (top-to-bottom) pixel index of the upper-left-hand corner of the box in the canvas we're going to draw this tree in private void paintSubtree(Graphics g, PureBinaryTree<Integer> tree, int treeHeight, int height, int width, int xOffset, int yOffset) { int nodeDiameter = Math.min((height/treeHeight)/2, width / 2); //in pixels int topLeftX = xOffset + width/2 - nodeDiameter/2; //draw the circle g.setColor(Color.BLACK); g.drawRect(topLeftX, yOffset, nodeDiameter, nodeDiameter); g.setColor(this.position.getColorFromInt(tree.getValue())); g.fillRect(topLeftX, yOffset, nodeDiameter, nodeDiameter); //draw the edges to the two children and the two subtrees if (tree.getLeftChild() != null) { //draw the left subtree PureBinaryTree<Integer> left = tree.getLeftChild(); int subtreeHeightUpperBound = treeHeight - 1; int subtreeAreaHeight = height - 2 * nodeDiameter; int subtreeAreaWidth = width / 2; int subtreeAreaXOffset = xOffset; int subtreeAreaYOffset = yOffset + 2 * nodeDiameter; this.paintSubtree(g, left, subtreeHeightUpperBound, subtreeAreaHeight, subtreeAreaWidth, subtreeAreaXOffset, subtreeAreaYOffset); } if (tree.getRightChild() != null) { //draw the right subtree PureBinaryTree<Integer> right = tree.getRightChild(); int subtreeHeightUpperBound = treeHeight - 1; int subtreeAreaHeight = height - 2 * nodeDiameter; int subtreeAreaWidth = width / 2; int subtreeAreaXOffset = xOffset + subtreeAreaWidth; int subtreeAreaYOffset = yOffset + 2 * nodeDiameter; this.paintSubtree(g, right, subtreeHeightUpperBound, subtreeAreaHeight, subtreeAreaWidth, subtreeAreaXOffset, subtreeAreaYOffset); } } }