javaswingactionlistenerdrawpaintcomponent

Draw shapes in Java based off if/else statements and action listener


I'm trying to figure out if there's any way to draw images (drawRect(), drawOval(), etc.) based on if/else statements or by using an ActionListener.

I don't want to post the complete problem because this is for an assignment, but for my own scenario:

If I have a button on a JPanel named "draw rectangle" and I have the x, y, width, and height from user input, is there any way I can attach an actionListener to "draw rectangle" that could somehow draw the rectangle using those values (passed by reference?).

I know I can use paintComponent, but I can't put that into the ActionListener and it seems to do things of its own accord and not based on a specific user's actions.

I don't really have any code for this because I can't figure out how to do it at all.


Solution

  • If I have a button on a JPanel named "draw rectangle" and I have the x, y, width, and height from user input, is there any way I can attach an actionListener to "draw rectangle" that could somehow draw the rectangle using those values (passed by reference?).

    The short answer is yes.

    Generally, you'll need to save the rectangle instructions in a model, and have the JPanel redraw the model when any of the shape buttons are pressed.

    Let's take your rectangle example. What do you need to know to draw a rectangle on a JPanel? You need a starting point (upper left) and an ending point (lower right). You can use a java.awt.Point to hold the starting and ending point. You can set the thickness of the line, in pixels. You can set the color of the rectangle, using a JColorChooser. You can also set the rectangle to be an outline or filled with the chosen color.

    That description will be similar for a line and a triangle. A circle is a little different, with a center point and a radius. As you can see, we already have a lot of information to keep track of just with these simple geometric shapes.

    Then there's the issue of the drawing surface itself. It's possible to have a drawing surface larger than your computer screen can show. You can put the drawing surface inside of a JScrollPane.

    All of these things must be determined so you can build the model of your application. You do this before you build the view using Swing components and the controller using action listeners.