Java Reference
In-Depth Information
public MyPanel () {
addMouseListener( new MouseAdapter () {
public void mousePressed (MouseEvent e ) {
if (e . getButton()==1) {
shapes .add( new MyShape( e . getPoint ( ) ) ) ;
repaint () ;
}} );
} public void paintComponent(Graphics g) {
super . paintComponent(g) ;
Graphics2D g2 = (Graphics2D) g ;
for (MyShape s :
shapes )
s . drawShape(g2) ;
Note that we can use the input event to determine the mouse key that is being pressed.
By calling the getButton method, we can determine which mouse button is pressed. The
method can return 1, 2, or 3, which corresponds to the left, middle, and right buttons of the
mouse being pressed, respectively. If the left mouse button is pressed, then we will create a
new object of type MyShape and add it to the ArrayList of shapes. Note that we can use
the code e.getPoint() to determine the coordinates of the mouse cursor when the mouse
event was generated. Since the event is registered within the panel, the coordinates will be
relative to the top left corner of the panel (and not the computer screen). We pass this
point to the constructor of the MyShape class in order to create a new shape with a single
At the end of the mousePressed method,wecallthe repaint method. This will redisplay
the picture. We need the picture redisplayed because we have added a new shape to it. The
repaint method leads to the eventual call of the paintComponent method (note that the
paintComponent method should not be called directly). In the paintComponent method, the
first line clears the drawing area. Next, a brush is created and the shapes in the ArrayList
are drawn.
In a GUI application, most listeners usually change the data to be displayed. After
this data is changed, the repaint method needs to be called. It in turn calls the
paintComponent method when possible and the picture is redisplayed. Recall that
the paintComponent method does not generate data, it simply displays it. The actual
data is usually generated in the listeners or the constructor methods.
Next, we need to register a mouse listener that will change the current shape when the
mouse is dragged. Here is the code.
class MyPanel extends JPanel {
ArrayList < MyShape > shapes = new ArrayList <> () ;
addMouseMotionListener( new MouseMotionAdapter ()
public void mouseDragged(MouseEvent e) {
if ((e. getModifiersEx() & MouseEvent.BUTTON1DOWN MASK) ! = 0 ) {
shapes . get(shapes . size () 1). addPoint(e . getPoint () ) ;
repaint () ;
Search WWH ::

Custom Search