Java Graphics Programming Study 1: Simple Swing Graphics

I have been playing with Java Swing graphics programming. As it turns out, it is fairly easy and yet extremely powerful. Points, lines, colors, curves, and shapes are all created easily from existing classes. All I have to do is learn how to use them.

I would love to take full credit for this code, but most of it was created by someone else. I have been using the “Custom Graphics Programming – Java Programming Tutorial” for the raw material for this study: specifically, example 3 was my starting point.

I reworked the code to make it more to update it, make it more to my liking, and understand it better. I also extensively commented it for a more clear understanding.

If you would like to download the code I wrote, it is available for download here. You can either pull the java files out of the zip file or import the project into the NetBeans IDE.

The code consists of two different java files. No other resources other than those included with the Java Development Kit (JDK) are needed.

File # 1

package GUI;

// imports are individually listed for clarity
import java.awt.BorderLayout;       // for JFrame use
import java.awt.Color;              // for use in drawing
import java.awt.Dimension;          // for specifying JPanel size
import java.awt.Graphics;           // variable type passed to methods
import java.awt.event.MouseAdapter;         // for mouse tracking
import java.awt.event.MouseEvent;           // for mouse tracking
import java.awt.event.MouseMotionAdapter;   // for mouse tracking
import java.util.ArrayList;         // multiuse storage class
import javax.swing.JFrame;          // for creating JFrames
import javax.swing.JPanel;          // for creating JPanels
import javax.swing.SwingUtilities;  // to access the Event Dispatch Thread

public class GraphicsStudy extends JFrame {
    // class variables
    ArrayList<MultipointLine> linesArray;   // stores completed lines
    JPanel graphicsPanel;                   // used for the drawing surface
    MultipointLine currentLine;             // an individual line in progress
    
    // constructor sets up the entire JFrame window
    public GraphicsStudy() {
        // initialize the new array that will store all the finished lines
        linesArray = new ArrayList();
        // GraphicsPanel is an inside class
        // it is a JPanel that will be used for drawing
        graphicsPanel = new GraphicsPanel(600, 400);
        
        // add a mouse click listener
        // every time the mouse is clicked, start a new line
        graphicsPanel.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent event) {
                currentLine = new MultipointLine(event.getX(), event.getY());
                linesArray.add(currentLine);
            }
        });
        
        // add a mouse motion listener
        // when the mouse is dragged (button down while moving),
        // add points to the line that was created when the button
        // was initially pressed
        // then call for a repaint of the graphics area
        graphicsPanel.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent event) {
                currentLine.addPoint(event.getX(), event.getY());
                repaint();
            }
        });
        
        // create the window, give it a title,
        // add the JPanel to the JFrame to use for drawing,
        // pack the JFrame,
        // use platform specific placement of the window,
        // and finally, make the window visible
        this.setTitle("Graphics Study");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.getContentPane().add(graphicsPanel, BorderLayout.CENTER);
        this.pack();                            // pack or set size
        this.setLocationByPlatform(true);
        this.setVisible(true);
    }
    
    
    public static void main(String[] args) {
        // all the main class has to do is call the
        // constructor for the JPanel and put it on
        // the event dispatch thread
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new GraphicsStudy();
            }
        });
    }
    
    // this is an inner class. It creates the Jpanel that
    // will be used as a drawing surface.
    class GraphicsPanel extends JPanel {
        
        // this constructor isn't really needed, but I am using
        // it to set the dimensions for the JPanel
        public GraphicsPanel(int rows, int cols) {
            this.setPreferredSize(new Dimension(rows, cols));
        }
        
        // Override the paintComponent method and put the
        // graphics creating code inside it.
        // Since it is an inner class, it can access the stored
        // lines from its parent class (GraphicsStudy).
        @Override
        protected void paintComponent(Graphics graphics) {
            // call the super method to paint the background
            super.paintComponent(graphics);
            
            // set the drawing line color
            // what can I say, Magenta is my color
            graphics.setColor(Color.MAGENTA);
            
            // draw the saved lines
            // lines were stored in the GraphicsStudy class
            // but can be accessed by this inner class
            for(MultipointLine line : linesArray) {
                line.drawMultipointLine(graphics);
            }
        }
    }
    
}

File # 2:

package GUI;

// import
import java.awt.Graphics;       // for drawLine function
import java.util.ArrayList;     // to store the points in the line

public class MultipointLine {
    private ArrayList<Integer> xArray;
    private ArrayList<Integer> yArray;
    
    // constructor creates a new line and sets the first point.
    // The constructor is called when the mouse button is pressed.
    public MultipointLine(int x, int y) {
        xArray = new ArrayList();
        yArray = new ArrayList();
        addPoint(x, y);
    }
    
    // add a point to the end of the x and y arrays.
    // these points will be used to draw a bunch of tiny lines
    final public void addPoint(int x, int y) {
        xArray.add(x);
        yArray.add(y);
    }
    
    // draw out the crazy line from the storage arrays
    public void drawMultipointLine(Graphics graphics) {
        for(int x = 0; x < xArray.size() - 1; ++x) {
            graphics.drawLine(xArray.get(x), yArray.get(x),
                    xArray.get(x+1), yArray.get(x+1));
        }
    }
}
Advertisements

Published by

Marisa

I am a writer of words, a thinker of thoughts, a changer of genders, and a queerer of life. I am an antagonist of the ordinary; and while I do tolerate it, I also look at it with contempt.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s