Java Genesis

Hints for Chapter 1: Getting Started

Problem 3: changing colours

Following is the code for the class PushingPanel as given in the file PushingPanel.java.

It is by no means obvious which part of this code is responsible for creating the red arrow. Have a look through the code and see if you can make a reasonable guess as to where the colour of the arrow is set to be red. When you have found what you think is the place, try changing the colour to blue, recompiling the class, and rerunning the application.

   import javax.swing.*;
   import java.awt.*;

   public class PushingPanel extends JPanel {

	/* Creates a square for the Puzzle.*/
	
	// instance variable
	private String cross = "X";
	public boolean isFree = false;
	private boolean isCross = false;
	public boolean isBox = false;
	private boolean isRightArrow = false;
	private int [ ] rxs = {5,30,30,45,30,30,5};
	private int [ ] rys = {20,20,10,25,40,30,30};
	private boolean isDownArrow = false;
	private int [ ] dxs = {30,30,40,25,10,20,20};
	private int [ ] dys = {5,30,30,45,30,30,5};
	private boolean isLeftArrow = false;
	private int [ ] lxs = {45,20,20,5,20,20,45};
	private int [ ] lys = {30,30,40,25,10,20,20};
	private boolean isUpArrow = false;
	private int [ ] uxs = {20,20,10,25,40,30,30};
	private int [ ] uys = {45,20,20,5,20,20,45};
	private Color boxColour = Color.blue;
	private Color crossColour = Color.green;
	
	// constructor
	public PushingPanel ( ) {
	   setBackground(Color.white);
  	}
    
  	public void paintComponent (Graphics g) {
	   super.paintComponent(g);
  	   if (isBox) {
  		g.setColor(boxColour);
  		g.drawRect(3, 3, 44, 44);
  		g.drawRect(4, 4, 42, 42);
  	   }
  	   if (!isFree) {
  		g.setColor(Color.gray);
  		g.fillRect(0, 0, 50, 50);
  	   }
  	   if (isCross) {
  		g.setColor(crossColour);
  		g.drawString(cross, 12, 40);
  	   }
  	   g.setColor(Color.red);
  	   if (isRightArrow) g.fillPolygon(rxs, rys,7);
  	   if (isDownArrow) g.fillPolygon(dxs, dys,7);
  	   if (isLeftArrow) g.fillPolygon(lxs, lys,7);
  	   if (isUpArrow) g.fillPolygon(uxs, uys,7);
  	}
	
	public void removeArrow ( ) {
	   isRightArrow = false;
	   isDownArrow = false;
	   isLeftArrow = false;
	   isUpArrow = false;
	   repaint();
	}
	public void setRightArrow ( ) {
	   isRightArrow = true;
	   repaint();
	}
	public void setDownArrow ( ) {
	   isDownArrow = true;
	   repaint();
	}
	public void setLeftArrow ( ) {
	   isLeftArrow = true;
	   repaint();
	}
	public void setUpArrow ( ) {
	   isUpArrow = true;
	   repaint();
	}
	public void removeBox ( ) {
	   isBox = false;
	   repaint();
	}
	public void setBox ( ) {
	   isBox = true;
	   repaint();
	}
	public void setCross ( ) {
	   isCross = true;
	   repaint();
	}
	public void setFree ( ) {
	   isFree = true;
	   repaint();
	}
	public void setRed ( ) {
	   boxColour = Color.red;
	   crossColour = Color.red;
	   repaint();
	}
   }

Try this before looking at the last hint.

Next Hint