Visual marker of mouse clicks using Java - java

I am creating a screen recorder software using Java. Almost 80% work has been completed. Now I need to create a visual marker of mouse clicks using Java. So that I can see in the playback video that where the mouse has been clicked. How can I do that?
Does anyone have any code example?

Very simple. Read the point where the mouse is clicked by the user with getX() and getY() methods of MouseListener. At the point, draw a oval with drawOval() methods of java.awt.Graphics class. Try the following code which I am sure solves your problem.
import java.awt.*;
import java.awt.event.*;
// no window closing code
public class MouseXY extends Frame implements MouseListener, MouseMotionListener
{
int x , y;
String str =" ";
public MouseXY()
{
setSize(500, 500);
setVisible(true);
addMouseListener(this); // register both the listeners with frame
addMouseMotionListener(this);
} // override the 5 abstract methods of ML
public void mouseEntered(MouseEvent e)
{
setBackground(Color.green);
x = e.getX();
y = e.getY();
str ="Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent e)
{
setBackground(Color.red);
x = e.getX();
y = e.getY();
str ="Mouse Exited";
repaint();
}
public void mouseClicked(MouseEvent e)
{
setBackground(Color.gray);
x = e.getX();
y = e.getY();
str ="Mouse Clicked";
repaint();
}
public void mouseReleased(MouseEvent e)
{
setBackground(Color.blue);
x = e.getX();
y = e.getY();
str ="Mouse Released";
repaint();
}
public void mousePressed(MouseEvent e)
{
setBackground(Color.lightGray);
x = e.getX();
y = e.getY();
str ="Mouse pressed";
repaint();
} // override the 2 abstract methods of MML
public void mouseDragged(MouseEvent e)
{
setBackground(Color.magenta);
x = e.getX();
y = e.getY();
str ="Mouse Dragged";
repaint();
}
public void mouseMoved(MouseEvent e)
{
setBackground(Color.yellow);
x = e.getX();
y = e.getY();
str = "Mouse Moved";
repaint();
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.fillOval(x , y , 10 , 10);
g.drawString(x +", "+ y , x , y);
g.drawString(str , x , y -10); // to draw the string above y coordinate
}
public static void main(String args[ ])
{
new MouseXY();
}
}

Related

Gradually incrementing stroke width in java

I have to draw the figure on the link in java as an assignment.The assignment
So far I have been able to draw the first arc using CubicCurve2D, as seen on the picture on the second link, but now I face the problem of incrementing the line width gradually.What I have achieved until now
Can anyone tell me if there is any way of achieving it. Thank you!
This is the code for the panel
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.geom.*;
import java.awt.image.*;
public class GraphicsDemo extends JPanel {
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.BLACK);
Graphics2D g2D = (Graphics2D) g;
g2D.setPaint(new Color(150,250, 187));
g2D.setStroke(new BasicStroke(1));
//g2D.drawArc(-50,50,300,300,0,90);
CubicCurve2D cubic = new CubicCurve2D.Double(0,230,80,90,130,220,80,190);
g2D.draw(cubic);
}
}
This is the code of the frame
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JFrame implements MouseListener, MouseMotionListener{
GraphicsDemo graphicDemo = new GraphicsDemo();
int x, y;
String str="";
public void mousePressed(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Pressed";
System.out.println("Coordinates of x: " + x + " , coordinates of y :" +y);
repaint();
}
public void mouseReleased(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Released";
repaint();
}
public void mouseClicked(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Clicked";
repaint();
}
public void mouseEntered(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Exited";
repaint();
}
// override MouseMotionListener two abstract methods
public void mouseMoved(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Moved";
repaint();
}
public void mouseDragged(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse dragged";
repaint();
}
public Test()
{
this.setSize(420,420);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(graphicDemo);
this.setVisible(true);
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
public static void main(String[] a){
new Test();
}
}

Implement in JAVA a rectangle shape feature like in Paint

I want to implement a Rectangle shape feature exactly as in Paint in JAVA. I have built a program as following. I have built a class MyPaint where buttons and frame are defined. I have built another class inside the same program PadDraw, where a drawing pad is created where I can draw with pencil like in Paint. Then I have another class outside the program DrawRect where the rectangle shape feature is created.
I want to know if there is a way to integrate the rectangle in a way that if I click a button "Rectangle", the way of drawing should change and instead of drawing with pencil, I should draw rectangle shapes exactly like in Paint when the rectangle shape is pressed.
The piece of code for PadDraw class is as following:
class PadDraw extends JComponent {
private Image image;
private Graphics2D graphics2D;
private int currentX , currentY , oldX , oldY ;
public PadDraw(){
setDoubleBuffered(false);
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
oldX = e.getX();
oldY = e.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
currentX = e.getX();
currentY = e.getY();
if(graphics2D != null)
graphics2D.drawLine(oldX, oldY, currentX, currentY);
repaint();
oldX = currentX;
oldY = currentY;
}
});
}
public void paintComponent(Graphics g){
if(image == null){
image = createImage(getSize().width, getSize().height);
graphics2D = (Graphics2D)image.getGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
clear();
}
g.drawImage(image, 5, 5, null);
}
While the piece of code of DrawRect class that I want to integrate in the program where MyPaint and PadDraw class are located is as following:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DrawRect extends JPanel {
int x, y, x2, y2;
public static void main(String[] args) {
JFrame f = new JFrame("Draw Box Mouse 2");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(new DrawRect());
f.setSize(300, 300);
f.setVisible(true);
}
DrawRect() {
x = y = x2 = y2 = 0; //
MyMouseListener listener = new MyMouseListener();
addMouseListener(listener);
addMouseMotionListener(listener);
}
public void setStartPoint(int x, int y) {
this.x = x;
this.y = y;
}
public void setEndPoint(int x, int y) {
x2 = (x);
y2 = (y);
}
public void drawPerfectRect(Graphics g, int x, int y, int x2, int y2) {
int px = Math.min(x,x2);
int py = Math.min(y,y2);
int pw=Math.abs(x-x2);
int ph=Math.abs(y-y2);
g.drawRect(px, py, pw, ph);
}
class MyMouseListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
setStartPoint(e.getX(), e.getY());
}
public void mouseDragged(MouseEvent e) {
setEndPoint(e.getX(), e.getY());
repaint();
}
public void mouseReleased(MouseEvent e) {
setEndPoint(e.getX(), e.getY());
repaint();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
drawPerfectRect(g, x, y, x2, y2);
}
}

Why can't I just use MouseAdapter, not MouseMotionAdapter?

My application's window can be moved around by dragging its menubar.
However, I don't understand why I have to use MouseMotionAdapter() to implement this feature.
Both classes have the method: mouseDragged(), so I erased MouseMotionAdapter and move the function into the MouseAdapter(). I could not drag the window anymore. Why?
This code works perfectly.
menuBar.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
}
});
//마우스로 매뉴를 잡고 움직일 수 있게 해주는 코드.
menuBar.addMouseMotionListener(new MouseMotionAdapter(){
#Override
public void mouseDragged(MouseEvent e) {
int x = e.getXOnScreen();
int y = e.getYOnScreen();
setLocation(x - mouseX, y - mouseY);
}
});
However, this doesn't
menuBar.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
}
#Override
public void mouseDragged(MouseEvent e) {
int x = e.getXOnScreen();
int y = e.getYOnScreen();
setLocation(x - mouseX, y - mouseY);
}
});
Thank you for your support
You can just use a MouseAdapter, but you have to call addMouseMotionListener so that mouse-motion events will get sent to it.
MouseAdapter ma = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
}
#Override
public void mouseDragged(MouseEvent e) {
int x = e.getXOnScreen();
int y = e.getYOnScreen();
setLocation(x - mouseX, y - mouseY);
}
});
menuBar.addMouseListener(ma);
menuBar.addMouseMotionListener(ma);
Only a listener registered with addMouseMotionListener will be sent mouse-motion events, like dragging.
From the MouseAdapter docs:
Create a listener object using the extended class and then register it with a component using the component's addMouseListener, addMouseMotionListener, addMouseWheelListener methods.

java mouselistener on Line2d vector

I am not very experimented with listeners. I have a Vector of Line2D (representating a floorplan walls). I draw them in a JFrame.
I try to set a listener on those lines to be able to set them (change color etc) on click.
I am lost because I don't really know where to put the listener. I tried many things I found on many forums but nothing works really.
Thanks.
Edit1:
hi thank you for your answer it's a kind of big projects with many classes so i will post the code and describe how it wokrs . First . I import an image with a floorplan. I have a class with Actions that extends AbstractAction. I use opencv for for lines extraction . I store the extracted lines in a Vector of Walls (class i created).
Vector<wall> walls
And here is my wall class
//a wall is represented by 2 points (pInitial and pFInal)
private Point pInitial, pFinal;
private double wallAttenuation;
private int wallType;
public wall(Point p1, Point p2) {
// p1 is lower by the height than p2
if (p1.getY() > p2.getY()) {
pInitial = p2;
pFinal = p1;
} else {
pInitial = p1;
pFinal = p2;
}
}
//method to set the attenuation of the wall
public void setWallAttenuation(double a) {
wallAttenuation = a;
}
//methods to set both ends of the wall
public void setPInitial(Point P1) {
pInitial.x=(int)P1.getX();
pInitial.x=(int)P1.getY();
}
public void setPFinal(Point P2) {
pFinal.x=(int)P2.getX();
pFinal.x=(int)P2.getY();
}
//methods to get wall attributes (attenuation , ends and type)
public double getWallAttenuation() {
return wallAttenuation;
}
public Point getPInitial() {
return pInitial;
}
public Point getPFinal() {
return pFinal;
}
public void setWallType(int type) {
wallType = type;
}
public int getWallType() {
return wallType;
}
now in my importAction class, and after processing I have this vector of walls (each wall defiened by start and end point . After that , I open a new Frame in which i draws the lines. I want to be able to click on each wall for further modifications.
First i tried to create a Frame class with mouse event handling like this :
public class CreateJFrameWindowWithMouseEventHandling extends JFrame implements MouseMotionListener,MouseListener {
private static final long serialVersionUID = 1L;
public CreateJFrameWindowWithMouseEventHandling() {
setTitle("Walls calibration");
addMouseListener(this);
}
#Override
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
System.out.println("Mouse Clicked at X: " + x + " - Y: " + y);
}
#Override
public void mouseEntered(MouseEvent e) {
int x = e.getX();
int y = e.getY();
System.out.println("Mouse Entered frame at X: " + x + " - Y: " + y);
}
#Override
public void mouseExited(MouseEvent e) {
int x = e.getX();
int y = e.getY();
System.out.println("Mouse Exited frame at X: " + x + " - Y: " + y);
}
#Override
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
System.out.println("Mouse Pressed at X: " + x + " - Y: " + y);
}
#Override
public void mouseReleased(MouseEvent e) {
int x = e.getX();
int y = e.getY();
System.out.println("Mouse Released at X: " + x + " - Y: " + y);
}
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
int x = e.getX();
int y = e.getY();
System.out.println("Mouse at X: " + x + " - Y: " + y);
repaint();
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new CreateJFrameWindowWithMouseEventHandling();
//Display the window.
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
but i guess it wasnt the right solution . next thing i tried was to create JPanel browse the vector , draw the current line and add a listener. to check if it works i change the cursor if the mouse is over a line :
JFrame wallsEdit = new JFrame("Walls Calibration");
wallsEdit.add(new JPanel() {
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
for(int i=0;i<walls.size();i++)
{
Point p1 = walls.get(i).getPInitial();
Point p2 = editor.walls.get(i).getPFinal();
g2.setColor(Color.black);
g2.setStroke(new BasicStroke(10));
g2.drawLine((int)p1.getX(),(int)p1.getY(), (int)p2.getX(),(int)p2.getY());
walls.get(i).addMouseListener(new MouseAdapter() {
public void mouseMoved(MouseEvent e) {
Point CursorPoint= MouseInfo.getPointerInfo().getLocation();
double x = CursorPoint.getX();
double y = CursorPoint.getY();
Line2D.Double current = new Line2D.Double(p1.getX(),p1.getY(),p2.getX(),p2.getY()) ;
if(current.intersectsLine(x, y, x, y))
{ setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
} else { setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
repaint();
});
}
}
}, BorderLayout.CENTER);
wallsEdit.setAlwaysOnTop(true);
wallsEdit.setVisible(true);
wallsEdit.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
and of course this doesnt work. so tried another thing. i declared my Wall class extends Component and implements mouseMotionListener and MouseListener. inside I wrote the mouseMoved event like for the panel .
hope that i gave all needed details . any help would be appreciated thank you very much

Java program to paint shows nothing

Using eclipse, I wrote a program trying to copy mspaint in Windows,there is no errors when build or run, I only complete several functions to test if it can be paint.
I wrote the class named "drawings" to sotre drawings which has been paint,
if I set current=0,it shows nothing ; if I set current=1, a circle shows up but when I release mouse,the circle disappear.
import java.awt.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.*;
public class MyDraw extends JFrame{
static int current = 0; // choice of different drawings, 0 means pencil
// 1 means circle
static int index=0; // the number of drawings
static int R,G,B; // the color of drawings
static float Stroke=17.0f; // the stroke of drawings
JLabel statusBar = new JLabel();// show the state of mouse
drawings []indexList=new drawings[5000];// store drawings to paint
DrawArea drawArea = new DrawArea();
public MyDraw(){
R=G=B=0;// initialize color
//add components to main window
add(drawArea);
setVisible(true);
setSize(1000,1000);
createNewItem(); // new a drawing
add(statusBar, BorderLayout.SOUTH);
show();
}
// new a drawing
public void createNewItem(){
switch(current){
case 0 :indexList[index]=new pencil();break;
case 1 :indexList[index]=new circle();break;
}
}
public static void main(String args[]){
new MyDraw();
}
// the panel to paint on
class DrawArea extends JPanel{
public DrawArea(){
setBackground(Color.white);
setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
addMouseListener(new MousePolice1());
addMouseMotionListener(new MousePolice2());
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d =(Graphics2D)g;
for(int j=0;j<=index;j++){
pass(indexList[index],g2d);
}
}
public void pass(drawings i,Graphics2D g2d){
i.draw(g2d);
}
}
class MousePolice2 extends MouseAdapter{
public void mouseDragged(MouseEvent e){
statusBar.setText(" Mouse Dragged #:[" + e.getX() +
", " + e.getY() + "]");
if (current == 0) {
indexList[index - 1].x1 = indexList[index].x2 =
indexList[index].x1 = e.getX();
indexList[index - 1].y1 = indexList[index].y2 =
indexList[index].y1 = e.getY();
index++;
createNewItem();
} else {
indexList[index].x2 = e.getX();
indexList[index].y2 = e.getY();
}
repaint();
}
}
class MousePolice1 extends MouseAdapter{
public void mousePressed(MouseEvent e){
statusBar.setText(" Mouse Pressed #:[" + e.getX() +
", " + e.getY() + "]");
indexList[index].x1 = indexList[index].x2 = e.getX();
indexList[index].y1 = indexList[index].y2 = e.getY();
if (current == 0 ) {
indexList[index].x1 = indexList[index].x2 = e.getX();
indexList[index].y1 = indexList[index].y2 = e.getY();
index++;
createNewItem();
}
}
public void mouseReleased(MouseEvent e){
statusBar.setText(" Mouse Released #:[" + e.getX() +
", " + e.getY() + "]");
if (current ==0) {
indexList[index].x1 = e.getX();
indexList[index].y1 = e.getY();
}
indexList[index].x2 = e.getX();
indexList[index].y2 = e.getY();
repaint();
index++;
createNewItem();
}
}
}
//the father
class drawings implements Serializable{
int x1,x2,y1,y2;
void draw(Graphics2D g2d){}
}
// the drawing pencil
class pencil extends drawings{
void draw(Graphics2D g2d){
g2d.setPaint(new Color(MyDraw.R,MyDraw.G,MyDraw.B));
g2d.setStroke(new BasicStroke(MyDraw.Stroke,
BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
g2d.drawLine(x1, y1, x2, y2);
}
}
class circle extends drawings
{
void draw(Graphics2D g2d) {
g2d.setPaint(new Color(MyDraw.R,MyDraw.G,MyDraw.B));
g2d.setStroke(new BasicStroke(MyDraw.Stroke));
g2d.drawOval(Math.min(x1, x2), Math.min(y1, y2),
Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)),
Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)));
}
}
Didn't I see it or where is the method show()?
Otherwise I just saw some programs which they need to do something like this with the windows:
setVisible(true);

Categories