Home Tutorial Java Swing Java Swing: Draw rectangle on mouse click

 
 

Share on Google+Share on Google+
Java Swing: Draw rectangle on mouse click
Posted on: September 25, 2012 at 12:00 AM
Advertisement
In this tutorial, you will learn how to draw a rectangle on mouse click.

Java Swing: Draw rectangle on mouse click

In this tutorial, you will learn how to draw a rectangle on mouse click.

Sometimes, there is a need of mouse clicks in swing applications instead of buttons. To add this mouse interaction, Java has provide an interface MouseListener. When the user clicks a mouse on JPanel, three kinds of MouseEvents are generated mousePressed, mouseReleased and mouseClicked. These are actually the methods of MouseListener interface.

In the given example, we are going to draw a rectangle by clicking the mouse at various places in the panel's drawing area. So we need to trap mouse events. For this, we have used mouseClicked() method along with the mouseReleased() method. By mouseClicked method we, have easily draw a rectangle on panel and  the method mouseReleased allowed us to erase the previous rectangle from the panel. The method g.drawRect() of Graphics class draws the rectangle on the panel.

Example

import java.awt.*;
import java.awt.Point;
import javax.swing.*;
import java.awt.event.*;

public class DrawRectangleOnMouseClick extends JPanel{

     MouseHandler mouseHandler = new MouseHandler();
     Point p1 = new Point(0, 0);
     Point p2 = new Point(0, 0);
     boolean drawing;

    public DrawRectangleOnMouseClick(){
        this.setPreferredSize(new Dimension(500, 400));
        this.addMouseListener(mouseHandler);
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawRect(p1.x, p1.y, p2.x, p2.y);
    }

    private class MouseHandler extends MouseAdapter {

        public void mouseClicked(MouseEvent e) {
            drawing = true;
            p1 = e.getPoint();
            p2 = p1;
            repaint();
        }

        public void mouseReleased(MouseEvent e) {
            drawing = false;
            p2 = e.getPoint();
            repaint();
        }
    }

    public static void main(String[] args) {
        JFrame f = new JFrame("Draw Rectangle On Mouse Click");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new DrawRectangleOnMouseClick());
        f.pack();
        f.setVisible(true);
    }
}

Output:

Advertisement

Related Tags for Java Swing: Draw rectangle on mouse click:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 25, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com