Source Code:
import objectdraw.*;
import java.awt.*;
/*
*Lisa Ballesteros adapted from JAEA
*
*Illustrates the use of the if-else statement.
*
* Tallies votes for candidates by assigning clicks on the right-side
* of the canvas to 'candidate A' and clicks on the left-side of the
* canvas to 'candidate B'. The tally is printed to the canvas.
*
*/
public class Voting extends WindowController {
// Coordinates of canvas, including x-coord of middle
private static final int MID_X = 300;
private static final int TOP = 0;
private static final int BOTTOM = 400;
// x coordinates of A and B text messages
private static final int TEXT_A_X = 20;
private static final int TEXT_B_X = MID_X + 20;
// y coordinates of instructions and vote count info
private static final int INSTRUCTION_Y = 180;
private static final int DISPLAY_Y = 220;
private int countA = 0; // Number of votes for A
private int countB = 0; // Number of votes for B
private Text infoA; // Display of votes for A
private Text infoB; // Display of votes for B
// Create displays with instructions on how to vote
public void begin() {
new Text( "Click on the left side to vote for candidate A.",
TEXT_A_X, INSTRUCTION_Y, canvas );
new Text( "Click on the right side to vote for candidate B.",
TEXT_B_X, INSTRUCTION_Y, canvas );
infoA = new Text( "So far there are " + countA + " vote(s) for A.",
TEXT_A_X, DISPLAY_Y, canvas );
infoB = new Text( "So far there are " + countB + " vote(s) for B.",
TEXT_B_X, DISPLAY_Y, canvas );
new Line( MID_X, TOP, MID_X, BOTTOM, canvas );
}
// Update votes and display vote counts
public void onMouseClick( Location point ) {
if ( point.getX() < MID_X ) {
countA++;
infoA.setText( "So far there are " + countA + " vote(s) for A." );
} else {
countB++;
infoB.setText( "So far there are " + countB + " vote(s) for B." );
}
}
}