java mouselistener on Line2d vector - java

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

Related

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);

When clicking label appear 2 times

I try to do make when we click the frame, it shows the coordinates of the click point. And i did this:
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
j1.setLocation(x, y);
j1.setText("(" + x + ", " + y + ")");
}
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
j1.setLocation(x, y);
j1.setText("(" + x + ", " + y + ")");
}
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
But when i click it shows the coordinates first at the center then the click point, 2 times. But i just want only one and at the click point. Where did i mistake, what shoul i do?
Just use mousePressed and that's it. When you click the mouse, 3 methods are often called -- mousePressed, mouseReleased and if the mouse does not move between press and release, mouseClicked. You want to respond to just one of these methods.
So change to:
public void mouseClicked(MouseEvent e) {} // leave this empty
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
j1.setLocation(x, y);
j1.setText("(" + x + ", " + y + ")");
// also be sure to tell your container to re-position components
revalidate();
repaint();
}
As a side recommendation, note that rather than having a class implement MouseListener, you could have it extend MouseAdapter, and that way your class wouldn't have to have all those empty MouseListener interface methods.
For example:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class MousePosition extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
// format String for display String
protected static final String FORMAT = "(%d, %d)";
private int xPos = -40;
private int yPos = -40;
private String displayText = "";
public MousePosition() {
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
xPos = e.getX();
yPos = e.getY();
// use FORMAT String to create our display text
displayText = String.format(FORMAT, xPos, yPos);
repaint();
}
});
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(displayText, xPos, yPos);
}
private static void createAndShowGui() {
MousePosition mainPanel = new MousePosition();
JFrame frame = new JFrame("MousePosition");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Java JFrame Bouncing Ball Physics Simulation- Ball Motion Conflicts Upon Creation of Creation

So, right now, I'm able to create multiple balls and update them all properly through a Vector of objects and a for loop to update each object independently. The problem is that for every ball after the first, the ball that is created seems to affect the momentum and position of the other balls, causing all the balls to abruptly change their flight paths.
Code for creating frame and managing ball creation based on mouselistener:
public class FrameCreation extends JFrame{
static Vector<BallCreate> ballObjects = new Vector<BallCreate>();
static Timer timer;
Point m1;
Point m2;
static JFrame frame1;
static mouseHandler mouse;
public static void main(String args[]){
FrameCreation frame = new FrameCreation();
frame1 = new JFrame("Phyiscs Test");
frame1.setVisible(true);
frame1.setSize(520,530);
frame1.setDefaultCloseOperation(frame1.EXIT_ON_CLOSE);
mouse = frame.new mouseHandler();
frame1.addMouseListener(mouse);
}
public class mouseHandler extends JPanel implements MouseListener{
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
m1 = e.getPoint();
System.out.println("Mouse pressed");
}
#Override
public void mouseReleased(MouseEvent e) {
m2 = e.getPoint();
Thread queryThread = new Thread(){
double vX = m2.getX() - m1.getX();
double vY = m2.getY() - m1.getY();
public void run(){
createBall(m1.getX(),m1.getY(),vX,vY);
}
};
queryThread.start();
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
public void createBall(double posX, double posY, double vX, double vY){
BallCreate newBall = new BallCreate(posX,posY,50,vX,vY);
ballObjects.add(newBall);
frame1.add(newBall);
frame1.revalidate();
newBall.repaint();
}
}
Code for drawing and updating balls:
public class BallCreate extends JPanel {
Timer timer;
int diam;
Color color;
double vX, vY, posX, posY;
final double G = 30;
public BallCreate(double posX, double posY, int diam, double vX, double vY){
this.posX = posX;
this.posY = posY;
this.vX = vX;
this.vY = vY;
this.diam = diam;
color = getRandomColor();
timer = new Timer(100, new MovementUpdate());
timer.start();
}
public void drawing(){
repaint();
}
public void motionUpdate(){
for(BallCreate ball : FrameCreation.ballObjects){
double t = 0.1;
double dX = ball.vX*t;
double dY = (ball.vY + G*t)*t;
double v2Y = G*t + ball.vY;
System.out.println("Ball v2y: " + ball.vY);
ball.posX = ball.posX + dX;
ball.posY = ball.posY + dY;
vY = v2Y;
drawing();
wallCollisionCheck();
}
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
for(BallCreate ball : FrameCreation.ballObjects){
g.setColor(ball.color);
//System.out.println("pos X: " + posX);
//System.out.println("pos Y: " + posY);
g.fillOval((int)ball.posX, (int)ball.posY,
ball.diam ,ball.diam);
}
}
public void wallCollisionCheck(){
for(BallCreate ball : FrameCreation.ballObjects){
double botBound = 500-(ball.posY + ball.diam);
if((botBound <=0 && vY>=0)|| (ball.posY <=0 && ball.vY <=0 )){
//System.out.println("Collision Noted");
//System.out.println("Prev vY: " + ball.vY);
ball.vY = ball.vY * -0.65;
//System.out.println("Post vY: " + ball.vY);
ball.posY = 460;
}
if((ball.posX <= 0 && ball.vX <= 0) || ((Math.abs(500 - ball.posX) <= 40)&& ball.vX >=0)){
ball.vX = ball.vX * -0.65;
}
drawing();
}
}
public Color getRandomColor(){
int R = (int)(255*Math.random());
int G = (int)(255*Math.random());
int B = (int)(255*Math.random());
Color c = new Color(R, G , B);
return c;
}
public class MovementUpdate implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
for(BallCreate ball : FrameCreation.ballObjects){
ball.motionUpdate();
}
}
}
}
I realize that the problem is slightly vague, but it's simply hard to describe without being able to show an image of what is happening. Any help is appreciated, and clarification of code can be done if necessary. Thanks.

How to add mouselistener on random drawn image in java?

I am building a game in Java and I need to add a mouselistener to an random drawn image in my game.
I made the image appear on random places every x seconds, when I click the image I would like to add 1 point to the scoreboard.
My code for the random image adding is:
Random rand = new Random();
private int x = 0;
private int y = 0;
Timer timer = new Timer(700, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
x = rand.nextInt(400);
y = rand.nextInt(330);
repaint();
}
});
public void mousePressed (MouseEvent me) {
// Do something here
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(achtergrond, 0, 0, this.getWidth(), this.getHeight(), null);
//g.drawImage(muisje, 10, 10, null);
g.drawImage(muisje, x, y, 100, 100, this);
}
I looked on google and found that I need to add a new class with a mouse event, but How do I add this? It's not clear enough because I'm just a beginner in Java.
You know where the image is drawn (x,y) and you know the size of the image (100,100), therefore to tell if the mouse click is inside the image you can do something like this:
public void mousePressed (MouseEvent me) {
int clickX = me.getXOnScreen();
int clickY = me.getYOnScreen();
if(clickX > x && clickX < x+100 && clickY > y && clickY < y+100) {
//the image has been clicked
}
repaint();
}
The class you're writing can then implement MouseListener.
EDIT in response to comment:
You don't need to link the code to the image, the component that you're writing should implement the mouse listener since this maintains the state and knows where the image is drawn. I would start out by looking at this link and implementing a basic MouseListener to print out the x and y co-ordinates of mouse clicks on your component:
http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html
Example component implementing Mouse Listener:
public class TestComponent extends JComponent implements MouseListener {
public TestComponent() {
this.addMouseListener(this);
}
#Override
public void mouseClicked(MouseEvent e) {
int clickedX = e.getX();
int clickedY = e.getY();
System.out.println("User Clicked: " + clickedX + ", " + clickedY);
}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
}
You need to register a MouseListener for your Gamevenster class. Instead of making the class implement MouseListener, just use a MouseAdapter, where you only have to implement the method mouseClicked. So in your constructor, you something like this
private JLabel scoreLabel = new JLabel("Score: " + score);
private int score = 0;
public Gamevenster() {
scoreLabel.setFont(new Font("impact", Font.PLAIN, 30));
scoreLabel.setForeground(Color.WHITE);
add(scoreLabel);
addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
int clickX = (int)p.getX();
int clickY = (int)p.getY();
if(clickX > x && clickX < x + 100 && clickY > y && clickY < y + 100) {
score++;
scoreLabel.setText("Score: " + score);
}
}
});
}

Visual marker of mouse clicks using 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();
}
}

Categories