JPAINT
PART 4 – CODING
THE TOOLS
In this part, we will implement a few basic tools. We will also setup a system by which more tools can fairly easily be implemented.
DISCUSSION
We will need to keep track of which tool is active in our program. We will also need to keep track of where we are in the process of using our tool (ie - when using the line tool, is the next click to specify the first point or is it to specify the final point). We’ll call this the mode of the application and it will be a String.
STEP 1
We will need to add the following datafield
that will keep track of the mode that the application is in:
public String mode;
STEP 2
Inside the actionPerformed(…)
method, inside the section where the line button was clicked, you need to add
the line:
mode="line_1";
The line_1
mode will mean that the line tool is selected but no clicks have occurred yet.
STEP 3
Inside the mouseClicked method, we now remove all content.
STEP 4
Inside the mouseClicked method, we will have the following setup.
if(mode.equals("line_1"))
{
…
}
else if (mode.equals("line_2"))
{
…
}
else if (mode.equals("circle_1"))
{
…
}
… and so on
STEP 5
Before continuing, we now need to add more data fields to
track the information needed to for the tools.
public int
x1;
public int y1;
public int x2;
public int y2;
STEP 6
Still inside the mouseClicked() method, if the mode is "line_1", we
need to store the click’s location in data fields x1 and y1.
We also need to set mode to "line_2".
STEP 7
Inside mouseClicked(), if the mode is "line_2", we need to do the
following:
·
store the click’s location in data fields x2
and y2;
·
draw the line using x1,y1,x2,y2;
·
repaint the canvas;
·
reset the line tool so it can
be used again by setting mode to "line_1".
STEP 8
You application should now work for the line tool. You should be able to draw many lines one
after another. Test it!
STEP 9
Do the same as the steps above for the rectangle
tool. The only challenge occurs when you
have to draw the rectangle because you need to provide the top left point along
with a width and height. So you will
have to use if statements to figure out if x1 or x2 are at the left side and is
y1 or y2 are at the top.
STEP 10
Test your application.
STEP 11
Do the same for other tools.