Rectangle 27 10

Not entirely sure I understand what's going wrong (just let me know if I'm off, so I can delete this :-)

Assuming you want to get the "real" component under the mouse (click/press) which triggered the start of editing, the trick is to do the conversion (from parent to editor coordinates) after the editor is added to its parent. That's guaranteed for shouldSelectCell, but not for isCellEditable (the latter being called before)

A recent answer in the context of a tree (should be similar enough) has some runnable example. Here's the relevant snippet:

/**
 * At this point in time the editing component is added to the table (not documented!) but
 * table's internal cleanup might not yet be ready
 */ 
@Override
public boolean shouldSelectCell(EventObject anEvent) {
    if (anEvent instanceof MouseEvent) {
        redirect((MouseEvent) anEvent);
    }
    return false;
}

private void redirect(final MouseEvent anEvent) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            MouseEvent ev = SwingUtilities.convertMouseEvent(anEvent.getComponent(), anEvent, editor);
            // at this point you have the mouse coordinates in the editor's system
            // do stuff, like f.i. findComponent
            ....
        }
    });
}

+1 In retrospect, one can see that p3 was showing the previous position.

@trashgod - good observation, missed that :-)

java - How can I get the component at the mouse click position, when u...

java swing jtable mouselistener tablecelleditor
Rectangle 27 1

You can get the table's row and column from the clicked point. Then call the same renderer's getTableCellRendererComponent method to get renderer component. Then correct point subtracting previous rows' heights from y and previous cells' widths from x. Then get proper child of rendered component.

But how do I get "proper child of rendered component"? I can't get it with findComponentAt() in this case either.

You can write own findComponentAt. Get all children and for each of them get bounds and check whether event x/y (corrected ones) are in the bounds.

java - How can I get the component at the mouse click position, when u...

java swing jtable mouselistener tablecelleditor
Rectangle 27 1

This is not an answer to your question but an explanation of the result you see: findComponentAt() returns null because "there is no child component at the requested point." MyCellPanel is located on a CellRendererPane used by JTable to speed rendering. There's an example of how it's used here.

java - How can I get the component at the mouse click position, when u...

java swing jtable mouselistener tablecelleditor
Rectangle 27 2

You can get source from here http://java-sl.com/JEditorPaneStructureTool.html It shows how to obtain text view bounds. First you get caret position for current mouse poiunter using viewToModel() method. Then go down the Views tree achieving leaf view and calcualte it's bounds. See this http://java-sl.com/tip_view_rectangle.html

If your mouse pointer in the view's rectangle then your mouse over text.

You can check whether the text in caret position is link and show your tooltip.

java - Formatting JEditorPane's cursor, tooltips, links - Stack Overfl...

java html swing hyperlink jeditorpane
Rectangle 27 2

As yoshi pointed out, the JLabel fills the entire content pane, so clicking anywhere in the content pane results in mouse events for the label.

1) You could also use GridBagLayout, instead of FlowLayout, in case you want the JLabel centered in its parent component (both vertically and horizontally). This solution is here.

final JPanel singleCenteredComponentJPanel = new JPanel(new GridBagLayout());
singleCenteredComponentJPanel.add(label);
frame.add(singleCenteredComponentJPanel);

2) If, furthermore, you want to ignore mouse clicks on any transparent pixels of the label icon (if any) you can do the following:

Use the BufferedImage.getRGB(int x, int y), BufferedImage.getColorModel() and ColorModel.getAlpha(int pixel) methods to determine the alpha value of the clicked pixel for each mouse event. If the alpha value is equal to 0, then the pixel is completely transparent, otherwise the alpha value is between 1 and 255 (both inclusive) which in turn means the pixel is not completely transparent. Example code follows below.

And instead of Image.getScaledInstance(...) to scale the image (which returns Image, but we need BufferedImage), use the solution provided here.

private static void loadImage() throws IOException {
    int newWidth = 80;
    int newHeight = 40;
    bi = ImageIO.read(RoundedButtonDemo.class.getResource("/resources/login.png"));
    bi = getScaledBufferedImage(bi, newWidth, newHeight);

}

public static BufferedImage getScaledBufferedImage(final Image img,
                                                   final int newWidth,
                                                   final int newHeight) {
    final GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
    final GraphicsDevice gdev = genv.getDefaultScreenDevice();
    final GraphicsConfiguration gcnf = gdev.getDefaultConfiguration();
    final BufferedImage simg = gcnf.createCompatibleImage(newWidth, newHeight, Transparency.TRANSLUCENT);

    //Painting input image to output image:
    final Graphics2D g2d = simg.createGraphics();
    g2d.drawImage(img, 0, 0, newWidth, newHeight, null); //@Docs "...is scaled if necessary.".
    g2d.dispose();

    return simg;
}

Also change the reference bi from Image to BufferedImage.

And then the MouseListener of the label:

private int count = 0;

@Override
public void mouseClicked(MouseEvent e) {
    if (e.getSource() == label) {

        //Get the mouse click position (in pixels),
        //relative to the top-left corner of label:
        final Point relativeClickPoint = e.getPoint();

        //Obtain alpha value from the TYPE_INT_ARGB pixel:
        final int pixel = bi.getRGB(relativeClickPoint.x, relativeClickPoint.y);
        final int alpha = bi.getColorModel().getAlpha(pixel);

        if (alpha > 0) { //Check if the pixel is not transparent.
            if (count % 2 == 0) {
                label.setText("Bye");
            } else {
                label.setText("Hello World");
            }
            count++;
        }
    }
}

Be aware for the above implementation: All transparent pixels of the image will be ignored (including transparent pixels "inside" the shape, if any). Which means the user could click in the center of the image and nothing would happen if the clicked pixel was completely transparent. So I made the assumption that this is not the case with your image here.

3) For the scaling of the Image, you can determine the new size with the method collapseInside(...):

/**
 * @param resultDim Output dimension (same aspect ratio as the original dimension, and inside containerDim).
 * @param originalDim Original dimension.
 * @param containerDim Dimension with the maximum width and maximum height.
 */
public static void collapseInside(final Dimension resultDim,
                                  final Dimension originalDim,
                                  final Dimension containerDim) {
    resultDim.setSize(originalDim);
    if (resultDim.width > containerDim.width) {
        //Adjusting height for max width:
        resultDim.height = ( resultDim.height * containerDim.width ) / resultDim.width;
        resultDim.width = containerDim.width;
    }
    if (resultDim.height > containerDim.height) {
        //Adjusting width for max height:
        resultDim.width = ( resultDim.width * containerDim.height ) / resultDim.height;
        resultDim.height = containerDim.height;
    }
}

With this method: a) Scaled Image's width will be less than or equal to container's size width (resultDim.width <= containerDim.width). b) Same for height (resultDim.height <= containerDim.height). c) Aspect ratio of the original Image size will be preserved in the new Image size (resultDim.width / resultDim.height == originalDim.width / originalDim.height). With Image.getScaledInstance(...) and the previous getScaledBufferedImage(...) the aspect ratio of the Image could change. So I edit the getScaledBufferedImage(...) to use collapseInside(...):

public static BufferedImage getScaledBufferedImage(final Image img,
                                                   final int newWidth,
                                                   final int newHeight) {
    final Dimension originalDim = new Dimension(img.getWidth(null), img.getHeight(null)),
                    containerDim = new Dimension(newWidth, newHeight),
                    resultDim = new Dimension();
    collapseInside(resultDim, originalDim, containerDim);

    final GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
    final GraphicsDevice gdev = genv.getDefaultScreenDevice();
    final GraphicsConfiguration gcnf = gdev.getDefaultConfiguration();
    final BufferedImage simg = gcnf.createCompatibleImage(resultDim.width, resultDim.height, Transparency.TRANSLUCENT);

    //Painting input image to output image:
    final Graphics2D g2d = simg.createGraphics();
    g2d.drawImage(img, 0, 0, resultDim.width, resultDim.height, null); //@Docs "...is scaled if necessary.".
    g2d.dispose();

    return simg;
}

Alternatively, you may also override the paintComponent(...) of JPanel and use Graphics.drawImage(...) to paint the Image bi to the JPanel like so:

@Override
protected void paintComponent(final Graphics g) {
    super.paintComponent(g);

    //Drawing the image:
    g.drawImage(img, 0, 0, null);

    //Drawing the text:
    //For centering the text, I used code from:
    //https://stackoverflow.com/questions/27706197/how-can-i-center-graphics-drawstring-in-java
    final FontMetrics metrics = g.getFontMetrics(g.getFont());
    final int x = (img.getWidth(null) - metrics.stringWidth(text)) / 2;
    final int y = (img.getHeight(null) - metrics.getHeight()) / 2 + metrics.getAscent();
    g.drawString(text, x, y);
}

Where img is bi and text is the text of the button (i.e. "Hello World" and "Bye"). Then add the MouseListener to the JPanel as is.

Complete code for this (as "RoundedButtonDemo1" class, in the same package):

import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Point;
import java.awt.Transparency;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public final class RoundedButtonDemo1 {
    private static BufferedImage bi;

    public static void main(String[] args) {
        try {
            loadImage();

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    createAndShowGUI();
                }
            });
        } catch (IOException e) {
            // handle exception
        }
    }

    private static void loadImage() throws IOException {
        int newWidth = 80;
        int newHeight = 40;
        bi = ImageIO.read(RoundedButtonDemo1.class.getResource("/resources/login.png"));
        bi = getScaledBufferedImage(bi, newWidth, newHeight);

    }

    public static BufferedImage getScaledBufferedImage(final Image img,
                                                       final int newWidth,
                                                       final int newHeight) {
        final Dimension originalDim = new Dimension(img.getWidth(null), img.getHeight(null)),
                        containerDim = new Dimension(newWidth, newHeight),
                        resultDim = new Dimension();
        collapseInside(resultDim, originalDim, containerDim);

        final GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
        final GraphicsDevice gdev = genv.getDefaultScreenDevice();
        final GraphicsConfiguration gcnf = gdev.getDefaultConfiguration();
        final BufferedImage simg = gcnf.createCompatibleImage(resultDim.width, resultDim.height, Transparency.TRANSLUCENT);

        //Painting input image to output image:
        final Graphics2D g2d = simg.createGraphics();
        g2d.drawImage(img, 0, 0, resultDim.width, resultDim.height, null); //@Docs "...is scaled if necessary.".
        g2d.dispose();

        return simg;
    }

    /**
     * @param resultDim Output dimension (same aspect ratio as the original dimension, and inside containerDim).
     * @param originalDim Original dimension.
     * @param containerDim Dimension with the maximum width and maximum height.
     */
    public static void collapseInside(final Dimension resultDim,
                                      final Dimension originalDim,
                                      final Dimension containerDim) {
        resultDim.setSize(originalDim);
        if (resultDim.width > containerDim.width) {
            //Adjusting height for max width:
            resultDim.height = ( resultDim.height * containerDim.width ) / resultDim.width;
            resultDim.width = containerDim.width;
        }
        if (resultDim.height > containerDim.height) {
            //Adjusting width for max height:
            resultDim.width = ( resultDim.width * containerDim.height ) / resultDim.height;
            resultDim.height = containerDim.height;
        }
    }

    private static class CustomButton extends JPanel {
        private Image img;
        private String text;

        public void setImage(final Image img) {
            this.img = img;
            final Dimension imgDim = new Dimension(img.getWidth(null), img.getHeight(null));
            setMinimumSize(imgDim);
            setPreferredSize(imgDim);
            repaint();
        }

        public Image getImage() {
            return img;
        }

        public void setText(final String text) {
            this.text = text;
            repaint();
        }

        public String getText() {
            return text;
        }

        @Override
        protected void paintComponent(final Graphics g) {
            super.paintComponent(g);

            //Drawing the image:
            g.drawImage(img, 0, 0, null);

            //Drawing the text:
            //For centering the text, I used code from:
            //https://stackoverflow.com/questions/27706197/how-can-i-center-graphics-drawstring-in-java
            final FontMetrics metrics = g.getFontMetrics(g.getFont());
            final int x = (img.getWidth(null) - metrics.stringWidth(text)) / 2;
            final int y = (img.getHeight(null) - metrics.getHeight()) / 2 + metrics.getAscent();
            g.drawString(text, x, y);
        }
    }

    private static void createAndShowGUI() {
        final JFrame frame = new JFrame();
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final CustomButton button = new CustomButton();
        button.setSize(new Dimension(5, 5));
        button.setImage(bi);
        button.setText("Hello World");
        //button.setHorizontalTextPosition(SwingConstants.CENTER);
        //button.setOpaque(false);
        //button.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        button.addMouseListener(new MouseListener() {

            private int count = 0;

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getSource() == button) {

                    //Get the mouse click position (in pixels),
                    //relative to the top-left corner of label:
                    final Point relativeClickPoint = e.getPoint();

                    //Obtain alpha value from the TYPE_INT_ARGB pixel:
                    final int pixel = bi.getRGB(relativeClickPoint.x, relativeClickPoint.y);
                    final int alpha = bi.getColorModel().getAlpha(pixel);

                    if (alpha > 0) { //Check if the pixel is not transparent.
                        if (count % 2 == 0) {
                            button.setText("Bye");
                        } else {
                            button.setText("Hello World");
                        }
                        count++;
                    }
                }
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mouseExited(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mousePressed(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mouseReleased(MouseEvent e) {
                // TODO Auto-generated method stub

            }
        });


        final JPanel singleCenteredComponentJPanel = new JPanel(new GridBagLayout());
        singleCenteredComponentJPanel.add(button);
        frame.add(singleCenteredComponentJPanel);

        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

Alternatively, if you want normal buttons, istead of labels, it seems here you can reshape buttons as well !

Other than that, I have also tried the following: 1) Using JLayeredPanes. There is a tutorial explaining them, and I guessed they could probably have a method to obtain the order of the visible pane for a given Point, or something like that, but they don't. 2) Using Container.getComponentAt(Point) and Container.findComponentAt(Point) in the MouseListener, but (as I found out after testing) these methods don't "see through" non-opaque (+transparent) pixels. 3) Searching for reshaping or translucency in JPanels (inspired by How to Create Translucent and Shaped Windows), but nothing found. 4) How to Decorate Components with the JLayer Class with first line saying:

... enables you to draw on components and respond to component events without modifying the underlying component directly.

seems promising, but I'm done here.

java - Create a clickable area around round JLabel image - Stack Overf...

java button jlabel
Rectangle 27 75

All the various popup background color are managed in Preferences > Java > Editor (like the one for the completion list popup in bug 133615). Other background colors are in General > Appearance > Colors and Font (type background in the filter field).

But the type popup seems to stick to a system color, which is why you see a black background. If this is truly the case, it is worth reporting as a bug.

The OP confirms it is not the case, actually:

It was in Preferences > C/C++ > Editor > Source hover background, and had to untick the "System default" (because the shown color was light-gray!)

/usr/share/themes/Ambiance/gtk-2.0/gtkrc

The relevant properties are tooltip_fg_color and tooltip_bg_color. Just search for these values, the position changes sometimes between releases, currently they are at the very top of the file.

tooltip_fg_color:#000000
tooltip_bg_color:#f5f5c5

Thanks. Don't know why I didn't find that after searching for a to-the-nerves time... It was in Preferences > C/C++ > Editor > Source hover background, and had to untick the "System default" (because the shown color was light-gray!)

Filter for "background" and go to C++ > Editor. Then Look under the list marked "Appearance color options" There you will find "Source hover background"

SWT_GTK3=0

ubuntu 10.04 - Eclipse, change popup text background color when hoveri...

eclipse ubuntu-10.04
Rectangle 27 0

You can get the table's row and column from the clicked point. Then call the same renderer's getTableCellRendererComponent method to get renderer component. Then correct point subtracting previous rows' heights from y and previous cells' widths from x. Then get proper child of rendered component.

But how do I get "proper child of rendered component"? I can't get it with findComponentAt() in this case either.

You can write own findComponentAt. Get all children and for each of them get bounds and check whether event x/y (corrected ones) are in the bounds.

java - How can I get the component at the mouse click position, when u...

java swing jtable mouselistener tablecelleditor
Rectangle 27 0

You don't need to use OpenGL specific libraries to do this, it can easily be accomplished with the Robot class, which contains a mouseMove() method - it does what it says on the tin.

As far as I'm aware both Robot and GLUTWarpPointer generate low level system events to move the mouse, thus achieving the same thing. I assume you're using JOGL which as far as I know doesn't expose the mouse moving functionality of GLUTWarpPointer, so if that's correct Robot is probably the only sensible option.

But that doesn't move it relative to the window, also, I need to know how to get the relative position of the mouse, btw, Component.getLocationOnScreen().x -How do I get the component if it's a window made in OpenGL

mouse - Set and get cursor position? JAVA w/ OpenGL - Stack Overflow

java mouse
Rectangle 27 0

Here is simple example with help of viewToModel() and getLineOfOffset() methods:

import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;

public class TestFrame extends JFrame {

    private JTextArea area;
    private JLabel l;


    public TestFrame() {
        init();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }


    private void init() {
        area = new JTextArea(5,5);
        area.addMouseMotionListener(getListener());
        l = new JLabel(" ");

        add(new JScrollPane(area));
        add(l,BorderLayout.SOUTH);
    }

    private MouseMotionListener getListener() {
        return new MouseMotionListener() {

            @Override
            public void mouseMoved(MouseEvent e) {

                int viewToModel = area.viewToModel(e.getPoint());
                if(viewToModel != -1){
                    try {
                        l.setText("line: "+(1+area.getLineOfOffset(viewToModel)));
                    } catch (BadLocationException e1) {
                        e1.printStackTrace();
                    }
                }
            }

            @Override
            public void mouseDragged(MouseEvent e) {
            }
        };
    }


    public static void main(String args[]) {
        new TestFrame();
    }

}

java - JTextArea - get the line of the current mouse position - Stack ...

java swing jtextarea
Rectangle 27 0

The problem has been fixed in the JDK8 Early Access Release. You can either download that version, or wait until it comes out. It was fixed in February as part of this ticket: RT-28129

I entered a ticket on the JavaFX Jira. You can follow it to see the status updates.

I've updated the demo to reflect your problem. It seemed to work when the transformation was using the z-axis (yesterday - different for me today), but not when the transformation was on the X or Y axes.

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Point3D;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.scene.transform.Rotate;
import javafx.scene.transform.RotateBuilder;
import javafx.stage.Stage;


public class JFXRotationXOrds  extends Application{

    @Override
    public void start(Stage primaryStage) throws Exception {
        VBox root = new VBox();
        final Rotate rotate = RotateBuilder.create().angle(80).pivotX(100).pivotY(100).pivotZ(0).axis(new Point3D(1,0,0)).build();
        root.getTransforms().add(rotate);
        root.setStyle("-fx-border-color: black; -fx-border-width:5; ");

        root.setOnMouseMoved(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent arg0) {
                if(arg0.getEventType() == MouseEvent.MOUSE_MOVED){
                    System.out.println(arg0.getSceneX() + "," + arg0.getSceneY());
                }
            }
        });

        Scene scene = new Scene(root, 200, 500);
        PerspectiveCamera camera = new PerspectiveCamera();
        scene.setCamera(camera);
        primaryStage.setTitle("BorderPane Example");
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args){
        Application.launch(args);
    }
}

In 2D it works fine but in 3D it doesn't, try to add a 3D rotate to your root and set perspective camera for your scene.

Ah - You did state rotating on the X axis, but your screenshot seemed to indicate rotation around the Z axis. I can see the problem now... I'm thinking you might be able to do some calculation using the formulas here (but haven't done the math to prove it): docs.oracle.com/javafx/2/api/javafx/scene/transform/Affine.html

@Eeliya - The problem seems to be fixed in the JDK8 Early Access Release. See answer's update for more details.

java - Get mouse position on node relative to it's coordinates and tra...

java javafx javafx-2
Rectangle 27 0

There should be a hit test function call in your if statement. The hit test function should translate from mouse coordinates to Cell coordinates for the current (i,j) position, and return a simple true or false. (And as soon as you get a true, you can exit both loops.)

You don't show how you are drawing the grid, though. If your grid starts at a position (xp,yp) and every cell has a height h and width w, you can easily convert mouse coordinates directly into cell coordinates:

cellx = (mousex - xp)/w
celly = (mousey - yp)/h

... where a cellx,celly < 0 or >= size would indicate a click outside the grid.

java - how to get element position in 2D array when mouse clicked? - S...

java arrays swing position mouselistener
Rectangle 27 0

As pointed out by @Hunter-mcmillen: you are confused about java operators.

public  void  mouseMoved(MouseEvent e) { 

        double distance1 = Math.pow((e.getX() - x1),2);
        double distance2 = Math.pow((e.getY() - y1),2); // Math.pow(a,b) == a^b (in a calculator)

        setdistance(Math.sqrt(distance1 + distance2));
        System.out.println(getdistance()); 
}

I really recommend that you read more carefully the Java operators before assuming how they work on the language.

I recommend also that you create a JPanel or JLabel for this picture, and then load such picture inside this new Jpanel or Label or other component.

public class Paint extends JPanel implements ActionListener {
    Mouse swim = new Mouse();
    Timer tm = new Timer(7, this);
    public void paintComponent(Graphics g) {
    // Try this:
    ImageIcon swimminghold = new ImageIcon(render.class.getResource("resources/Swimmingpoolns.png")); 
    swimmingpool = swimminghold.getImage();
    JLabel label = new JLabel();
    label.setIcon(swimminghold);
    label.addMouseMotionListener(swim);
    addMouseMotionListener(swim);
    label.addMouseMotionListener(swim);
    addMouseMotionListener(swim);

        //Do something

        /* ...*/
}

Ive updated the code however in "public void paintComponent(Graphics g) {" swim.getdistance() is still printing 0

the problem is that getdistance() is always returning 0 in "public void paintComponent(Graphics g).

Ive updated the code to show the loading of images , however moving away from that , any variables that are changed outside of public void paintComponent(Graphics g) will not update in public void paintComponent(Graphics g) no matter what i try;

in my case , in the Mouse class , i store a variable called distance I created a getter for this variable. Whenever I call this getter in public void paintComponent(Graphics g) it will always show 0 , not updating. This getter works anywhere else apart from public void paintComponent(Graphics g).

swing - Cannot get mouse position in Java - Stack Overflow

java swing mouseevent
Rectangle 27 0

Without knowing much about what is on the screen we can apply the following. As long as there is no offset from the edge of the canvas to where you rendered the cells you can use the follow, if there is offset, you will need to add it to the x,y coordinates.

int x = 201;  //You would use e.getX();
int y = 10;   //You would use e.getY();

int xWidth = 50;
int yWidth = 50;

//Divide by the width to get the array position
int xIndex = (int)Math.floor(x / xWidth);
int yIndex = (int)Math.floor(y / yWidth);

java - how to get element position in 2D array when mouse clicked? - S...

java arrays swing position mouselistener
Rectangle 27 0

Input input = gc.getInput();
int xpos = input.getMouseX();
int ypos = input.getMouseY();

Java - Slick2D/lwjgl get mouse position - Stack Overflow

java position mouse lwjgl slick2d
Rectangle 27 0

I have figured it out. I used the lwjgl.jar from the lwjgl-2.9.2 download folder and it worked. I guessed using the one that came with Slick2D was buggy or something. Maybe my set up was wrong from the start? Anyways, I got it to work.

Java - Slick2D/lwjgl get mouse position - Stack Overflow

java position mouse lwjgl slick2d
Rectangle 27 0

i do not want to get tho position of the mouse , its is a board game and i want to get the position of square , the user clicked on it .

@Michael Samir again to re_read comment by Andrew Thompson about SSCCE, edit your question with code in this form, then after you can want to something, otherwise this question (and with contraproductive comments) isn't answerable ...

java - in the mouse click method when i call the method get X() and ge...

java awt mouseevent mouselistener mouse-listeners
Rectangle 27 0

I decided to just make a translucent window the size of the screen (which is barely visible) and collected the mouse positions that way. It seemed to work, but I was hoping that I wouldn't have to paint an extra component.

  • User is able to see through the window and can click where one wants

java - How do I get the mouse position on click when it is outside of ...

java click mouse mouse-position
Rectangle 27 0

Ok Guys i found the solution now:

MouseInfo.getPointerInfo().getLocation().x - XYZ.getLocationOnScreen().x
 MouseInfo.getPointerInfo().getLocation().y - XYZ.getLocationOnScreen().y

with XYZ being the reference to the Frame / Panel / whatever being used

position - (Java) Get Mouse Coordinates Within Window - Stack Overflow

java position mouse