When clicking label appear 2 times - java

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

Related

how to drag an image around starting from the mouse position , in Java?

So I am a new Java programmer and I am trying to learn how to deal with GUI and moving images around using JLabel
public class MyJava extends JFrame implements MouseListener, MouseMotionListener {
JLabel aJLabel;
public MyJava() {
this.setLayout(null);
aJLabel = new JLabel();
ImageIcon aImageIcon = new ImageIcon(this.getClass().getResource("avatar.jpg"));
aJLabel.setIcon(aImageIcon);
aJLabel.setBounds(50, 50, 200, 150);
this.getContentPane().add(aJLabel);
this.addMouseListener(this);
this.addMouseMotionListener(this);
this.setTitle("Title");
this.setSize(700, 600);
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new MyJava();
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("mouseClicked, X=" + e.getX() + " ,Y=" + e.getY() + " ,Count=" + e.getClickCount());
}
#Override
public void mouseDragged(MouseEvent e) {
aJLabel.setBounds(e.getX()-120, e.getY()-120, 200, 150);
}
#Override
public void mousePressed(MouseEvent e) {
System.out.println("mousePressed");
}
#Override
public void mouseReleased(MouseEvent e) {
System.out.println("mouseReleased");
}
#Override
public void mouseEntered(MouseEvent e) {
System.out.println("mouseEntered");
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
System.out.println("mouseMoved");
}}
I am trying to lean how to :
1- start dragging from the mouse position that i click on ?
2-dragging only if the mouse is on the image bounds not on all JLabel ?
dragging only if the mouse is on the image bounds not on all JLabel ?
Add the listener to the label, not the frame.
start dragging from the mouse position that i click on ?
Determine the starting point when the label is clicked and calculate the change in mouse location with each event. Basic code is:
public class DragListener extends MouseInputAdapter
{
Point location;
MouseEvent pressed;
public void mousePressed(MouseEvent me)
{
pressed = me;
}
public void mouseDragged(MouseEvent me)
{
Component component = me.getComponent();
location = component.getLocation(location);
int x = location.x - pressed.getX() + me.getX();
int y = location.y - pressed.getY() + me.getY();
component.setLocation(x, y);
}
}
The code to use this class would be:
DragListener drag = new DragListener();
label.addMouseListener( drag );
label.addMouseMotionListener( drag );

Constantly updating JFrame text

I am new to java development, and decided to create a simple java project that outputs the X and Y coordinates of where the mouse is inside of a jframe. I am unsure how I would use a listener.
package main;
import java.awt.BorderLayout;
import java.awt.MouseInfo;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class Main {
public static void main(String[] args) {
jFrame();
}
public static void jFrame() {
JFrame myFrame = new JFrame("Screen Location");
myFrame.setVisible(true);
myFrame.setBounds(0, 0, 300, 100);
JLabel myText = new JLabel(""+ getTotal(),
SwingConstants.CENTER);
myFrame.getContentPane().add(myText, BorderLayout.CENTER);
}
private static String getTotal() {
for (int i = 0; i < 1;) {
int publicScreenValueX = MouseInfo.getPointerInfo().getLocation().x;
int publicScreenValueY = MouseInfo.getPointerInfo().getLocation().y;
String total = new String(publicScreenValueX + ", " + publicScreenValueY);
return total;
}
return null;
}
}
How would I be able to make the project constantly update the coordinates? Could someone provide a reference on how to do this?
Do note, this is without using a button, or without any input from the user, other than moving the mouse.
Here is an image of what this would look like:
Except the coordinates would always be updating.
Basically all you have to do in order to create a JFrame that handles mouse events is:
1 - Create a class that extends JFrame and implements MouseListener
2 - #Override mouseClicked, mouseEntered, mouseExited, mousePressed, mouseReleased to monitor the coresponding events. Now every time one of these events occures, the respective function will fire up.
Use MouseEvent.getX(), MouseEvent.getY() to get the coordinates of the window that the mouse event occurs.
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
public class CreateJFrameWindowWithMouseEventHandling extends JFrame implements MouseListener {
private static final long serialVersionUID = 1L;
public CreateJFrameWindowWithMouseEventHandling() {
setTitle("Simple Frame");
addMouseListener(this);
}
#Override
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
JOptionPane.showMessageDialog(null, "Mouse Clicked at X: " + String.valueOf(x) + " - Y: " + String.valueOf(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);
}
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);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I would advise on creating a new class that inherits from JFrame and all that, because it's way more Object Oriented friendly.
However, with your code, what you need to do is add a MouseMotionListener to your JFrame, implement all abstract methods and, on the method mouseMoved, change your myText Label's text;
Replace the method below with the one you currently have and it should work.
Please note that, java.awt.event.MouseMotionListener is only going to give you information about mouse movement inside your application window. For events that occur outside that window, you might want to check this other question:
Java mouse motion anywhere on screen
public static void jFrame() {
JFrame myFrame = new JFrame("Screen Location");
myFrame.setLocationRelativeTo(null);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // makes the application close when you close the JFrame
myFrame.setVisible(true);
myFrame.setBounds(0, 0, 300, 100);
JLabel myText = new JLabel(""+ getTotal(), SwingConstants.CENTER);
myFrame.getContentPane().add(myText, BorderLayout.CENTER);
myFrame.addMouseMotionListener(new MouseMotionListener(){
#Override
public void mouseDragged(MouseEvent e) {
// don't delete this method
// all abstract methods must be overridden
}
#Override
public void mouseMoved(MouseEvent e) {
myText.setText(getTotal());
}
});
}

Move a Graphic in Java,using keyboard arrows and mouseEvent

I'm a beginner in learning this.Doing a test by drawing a triangle and now I want to move it.it's not working so I want to ask what's my mistake.Sorry it's long.
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
public class Test extends JFrame {
private Triangle triangle;
private final int step = 10;
private Triangle keyboardPanel = new Triangle();
public static void main(String[] args)
{
Test t = new Test();
}
public Test()
{
setTitle("TRY TRY TRY");
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 500);
JPanel tripanel = new JPanel();
add(tripanel);
triangle = new Triangle();
tripanel.addKeyListener(null);
tripanel.addMouseListener(null);
tripanel.addMouseMotionListener(null);
setVisible(true);
}
static class move extends JPanel implements KeyListener,MouseListener, MouseMotionListener{
private int x = 210;
private int y = 210;
private Color color = Color.BLACK;
move()
{
addKeyListener(this);
addMouseListener(this);
addMouseMotionListener(this);
}
#Override
public void keyPressed(KeyEvent ke) {
int KeyCode = ke.getKeyCode();
System.out.println("key code is" +KeyCode);
/*switch (KeyCode)
{
case KeyEvent.VK_UP:
triangle.moveTriangle(-10, 0);
break;
case KeyEvent.VK_DOWN:
triangle.moveTriangle(10, 0);
break;
case KeyEvent.VK_LEFT:
triangle.moveTriangle(0, -10);
break;
case KeyEvent.VK_RIGHT:
triangle.moveTriangle(0, 10);
break;
}
repaint();*/
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
System.out.println("hello");
x = e.getX();
y = e.getY();
repaint();
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
System.out.println("hello123");
if(e.isControlDown())
color = Color.RED;
else
color = Color.BLACK;
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println(e.getPoint());
}
}
public void paint(Graphics g)
{
super.paint(g);
triangle.drawTriangle(g);
}
public void paintComponent(Graphics g)
{
super.paintComponents(g);
triangle.drawTriangle(g);
}
}
import java.awt.Graphics;
import javax.swing.JPanel;
public class Triangle {
private Point p1;
private Point p2;
private Point p3;
int numX;
int numY;
public Triangle()
{
p1 = new Point(200,200);
p2 = new Point(170,230);
p3 = new Point(230,230);
}
public void moveTriangle(int dx, int dy)
{
p1.move(dx, dy);
p2.move(dx, dy);
p3.move(dx, dy);
}
public void drawTriangle(Graphics g)
{
g.drawLine(p1.getX(), p1.getY(),p2.getX(),p2.getY());
g.drawLine(p2.getX(),p2.getY(),p3.getX(),p3.getY());
g.drawLine(p3.getX(), p3.getY(),p1.getX(),p1.getY());
}
}
public class Point {
private int x;
private int y;
public Point(int X, int Y)
{
x = X;
y = Y;
}
public void setX(int X)
{
x = X;
}
public void setY(int Y)
{
x = Y;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void move(int dx, int dy)
{
x +=dx;
y +=dy;
}
public String toString()
{
return("X = "+x+" Y= "+y);
}
}
there are lot of problems in your code .when you coding always test current code before go further.
you create a panel and add to the jframe .
JPanel tripanel = new JPanel();
add(tripanel);
but your graphical mechanism has written in move panel so you need to make a move panel instead of jpanel.
keylistners has added to panel but keylisners not get triggered because keylistners work when component is focused . it works for component like jtextfiled . but not for panels .you have to use keybinding .i have added keybind for rightarrow key ..you have to add it to other keys up ,down etc..
also move your paint method from jframe to move jpanel .
example code (run this code and press right arrow ->)
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class Test extends JFrame {
private Triangle triangle;
private final int step = 10;
private Triangle keyboardPanel = new Triangle();
public static void main(String[] args) {
Test t = new Test();
}
public Test() {
setTitle("TRY TRY TRY");
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 500);
JPanel tripanel = new move();
add(tripanel);
triangle = new Triangle();
setVisible(true);
}
class move extends JPanel implements MouseListener, MouseMotionListener {
private int x = 210;
private int y = 210;
private Color color = Color.BLACK;
move() {
addMouseListener(move.this);
addMouseMotionListener(move.this);
this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "moveright");
this.getActionMap().put("moveright", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
triangle.moveTriangle(10, 0);
repaint();
}
});
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
System.out.println("hello");
x = e.getX();
y = e.getY();
repaint();
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
System.out.println("hello123");
if (e.isControlDown()) {
color = Color.RED;
} else {
color = Color.BLACK;
}
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
//System.out.println(e.getPoint());
}
#Override
public void paint(Graphics g) {
super.paint(g);
triangle.drawTriangle(g);
}
}
class Triangle {
private Point p1;
private Point p2;
private Point p3;
int numX;
int numY;
public Triangle() {
p1 = new Point(200, 200);
p2 = new Point(170, 230);
p3 = new Point(230, 230);
}
public void moveTriangle(int dx, int dy) {
p1.move(dx, dy);
p2.move(dx, dy);
p3.move(dx, dy);
}
public void drawTriangle(Graphics g) {
g.drawLine(p1.getX(), p1.getY(), p2.getX(), p2.getY());
g.drawLine(p2.getX(), p2.getY(), p3.getX(), p3.getY());
g.drawLine(p3.getX(), p3.getY(), p1.getX(), p1.getY());
}
}
class Point {
private int x;
private int y;
public Point(int X, int Y) {
x = X;
y = Y;
}
public void setX(int X) {
x = X;
}
public void setY(int Y) {
x = Y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void move(int dx, int dy) {
x += dx;
y += dy;
}
public String toString() {
return ("X = " + x + " Y= " + y);
}
}
}
output >>

Java - boolean set to false with nothing telling it to do so

My boolean drawFlag is being set to false in my code with nothing visible actually telling it to change value to false. This is preventing the code inside method mouseDragged(mouseEvent) to execute. If someone could point out what's making the flag become false so this would stop happening? Thanks.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class DrawAndDrag {
public static void main(String[] args) throws InterruptedException {
GraphicsFrame window = new GraphicsFrame("Draw Rectangle");
window.init();
}
}
class GraphicsFrame extends JFrame {
public GraphicsFrame(String title) {
super(title);
}
public void init() {
Container pane = this.getContentPane();
pane.add(new GraphicsContent().init());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600, 600);
this.setVisible(true);
}
}
class GraphicsContent extends JPanel {
private int xStart, yStart;
private int width, height;
public JPanel init() {
this.setBackground(Color.WHITE);
this.addMouseListener(new MouseDrag());
this.addMouseMotionListener(new MouseDrag());
return this;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(xStart, yStart, width, height);
}
class MouseDrag implements MouseListener, MouseMotionListener {
private boolean drawFlag;
public void mousePressed(MouseEvent e) {
if(isOutside(e)) {
this.drawFlag = true;
xStart = e.getX();
yStart = e.getY();
width = 0; height = 0;
System.out.println(drawFlag);
}else {
// this.drawFlag = false;
}
}
public void mouseDragged(MouseEvent e) {
System.out.println(drawFlag);
if(drawFlag) {
width = e.getX() - xStart;
height = e.getY() - yStart;
repaint();
}
}
public boolean isOutside(MouseEvent e) {
int xMin = Math.min(xStart, xStart + width); int yMin = Math.min(yStart, yStart + height);
int xMax = Math.max(xStart, xStart + width); int yMax = Math.max(yStart, yStart + height);
if((e.getX() < xMin || e.getX() > xMax)
|| (e.getY() < yMin || e.getY() > yMax)) {
return true;
}else {
return false;
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
}
}
Try to move drawFlag attribute from the inner class MouseDrag to the outer class GraphicsContent as follow
class GraphicsContent extends JPanel {
private int xStart, yStart;
private int width, height;
private volatile boolean drawFlag;
// other code
}
However as you drag, the value is constantly being reported as being false
You've got two listeners. One is a motion listener:
this.addMouseListener(new MouseDrag());
this.addMouseMotionListener(new MouseDrag());
mousePressed will not be called on a motion listener, so it will always be false in the drag event.
I expect what you meant is this:
MouseDrag listener = new MouseDrag();
this.addMouseListener(listener);
this.addMouseMotionListener(listener);
Are you sure you need two MouseDrag elements? I.e. using something like
public JPanel init() {
this.setBackground(Color.WHITE);
MouseDrag md = new MouseDrag();
this.addMouseListener(md);
this.addMouseMotionListener(md);
return this;
}
I can at least plot a blue square....

In Java, my MouseMotionListener and MouseListener is detecting clicks, but not movement

so I am creating a java game and and here is my mouse's clicks are being detected but the mouseMoved is not being run at all. There is a print statement in the method which never gets run. I am really stuck because since the clicks are being registered across the window, there shouldn't be anything wrong with the mouse motion.
Is the mouse dependent on anything else because I really have no idea what is causing this.
Thanks.
public class Mouse implements MouseListener, MouseMotionListener{
private static int mouseX = -1;
private static int mouseY = -1;
private static int mouseB = -1;
public static int getX(){
return mouseX;
}
public static int getY(){
return mouseY;
}
public static int getB(){
return mouseB;
}
public void mouseMoved(MouseEvent e) {
System.out.println("Mouse Moved");
mouseX = e.getX();
mouseY = e.getY();
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
mouseB = e.getButton();
System.out.println(e.getX() + " " + e.getY());
}
public void mouseReleased(MouseEvent e) {
mouseB = -1;
}
public void mouseDragged(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {
}
}
Here is my game constructor which initiates everything.
public Game(){
//cCursor();
screen = new Screen(WIDTH, HEIGHT);
mouse = new Mouse();
keys = new Keyboard();
//level = new RandomLevel(64, 64);
level = Level.spawn;
TileCoord pSpawn = new TileCoord(20,66);
player = new Player(pSpawn.x(), pSpawn.y(), keys);
player.init(level);
addKeyListener(keys);
addMouseListener(mouse);
}
MouseMoitionListener is a different listener to MouseListener and needs to be registered separately...
Start by adding a call to addMouseMotionListener
addMouseListener(mouse);
addMouseMotionListener(mouse);
Have a look at How to Write a Mouse Listener for more details

Categories