ScribbleDriver Class
This is where most of the work is for this lab. The basic parts of the Swing GUI we are going to make are as follows:
-
Step 1: Create the actual application window, also known
as a top-level window. We are using a JFrame for
this. All Swing GUIs have at least one "top level" container, the most
common of which is the JFrame. The JFrame frame has already been declared for you, but you will need to instantiate it. The constructor takes a String for the window title. You should also use the method
setPreferredSize
to set the size of your window. -
Step 2: Create two subsections within the JFrame known as
JPanels. These are used to separate different GUI
components into different areas of your layout. A JPanel named canvas
(where the user will be able to draw) and a JPanel named colorPalette (which will hold the ColorButton objects that will change your pen colors) have already been declared for you. You will need to instantiate them, set their sizes, and add them to your JFrame. You can add the panels to your JFrame frame by using JFrame's
add
method. This takes in your JPanel and also the relative position where you want the JPanel to be located, using the BorderLayout class. With BorderLayout, you create layouts such as:BorderLayout.NORTH
and your colorPalette added to the JFrame atBorderLayout.SOUTH
. It's up to you. - Step 3: Create buttons for each of your pen colors and then add them to your JPanel colorPalette. This is very similar to adding JPanels to your JFrame. These colorButtons won't do anything initially; later you will write ActionListeners for each button to give them functionality.
- Step 4: Create a MouseListener for your JFrame. This will listen for mouse clicks in your whole application. Whatever you put in here will be executed when you click your mouse on the appropriate component. In this lab, you will have to get the last positions of your mouse cursor when you click your mouse. You should update the variables lastMouseX and lastMouseY here.
-
Step 5: Create a MouseMotionListener for
your JFrame. This will draw a line from your last mouse position to your
current one, when your mouse cursor moves. Step 5a, you can use the
following code to get the JFrame's graphics context. Suppose "frame" is a
JFrame object.
Graphics g = frame.getGraphics();
You can refer to this page on how to use Java 2D Graphics library. The useful methods that you will be using are:-
drawLine(int x1, int y1, int x2, int y2)
Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system. -
setColor(Color c)
Sets this graphics context's current color to the specified color.
-
- Step 6: Add action listeners to each of your color buttons. When your color button is clicked, set your pen color to be the button color.
- Step 7: Display the window.