0

Is there a method to get coordinates in the (x,y) format for a Jbutton similar to the pt.distance() method. The jbutton utilizes setLayout(null) and setBounds(x,y,0,0). How would I compare the results of a pt.distance() and Jbutton(x,y)?

Lastly, how is (x,y) calculated?

 Point pt = evt.getPoint();
    double u = pt.distance((double)x,(double)y);
    double k = st1.getAlignmentX();
    double p = st1.getAlignmentY();
    if(u > ){ // u has to be measured to (x,y) value of jbutton
    tim.setDelay(500);
    }
    if(u < ){
    tim.setDelay(100);
    }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
user1566796
  • 35
  • 2
  • 9

3 Answers3

3

If by pt.distance(), you are referring to the Point2D.distance() method then you could proceed like this:

Point location = button.getLocation(); // where button is your JButton object
double distance = pt.distance(location); // where pt is your Point2D object

Or:

double distance = pt.distance(button.getX(), button.getY());

The Point will then contain your button's x and y coordinate. If you are not using layouts, these values will be what you set them to. But if you are using layouts, then the LayoutManager of the parent is responsible for calculating the values.

In response to your edit: I don't understand what you are trying to do. Calling setLayout(null) on the JButton will not let you set the coordinates of the button, only it's children. I think this is what you are trying to achieve:

Point pt = evt.getPoint();
double distance = pt.distance(button);
int someLength = 100; // the distance away from the button the point has to be to decide the length of the delay    

if (distance < someLength) {
    tim.setDelay(500);
} else {
    tim.setDelay(100);
}
  • I'm trying to get my pointer to cause the button to move faster as the pointer gets closer. So I need the pointer values to remain, but I also need the values of the button that way I can compare the two values and determine if their in a certain range then the delay will either speed up or slow down. – user1566796 Oct 27 '13 at 05:44
2

Howabout getLocation, which returns the coordinate of a component on its parent component, or getLocationOnScreen, which returns the coordinate of the component on the display?


Your second question about how x and y are calculated, I'm not sure what you mean by 'calculated'. The coordinates will be relative to something. Usually either the parent component (like a JPanel on which the JButton is sitting) or a location on the screen (such as getLocation would return for a JFrame).

A method like Point.distance will subtract the two coordinates' x and y values and tell you the difference. This is just basic geometry.

For example, here is a method that will return the distance of a point from the center of a JButton:

public static double getDistance(Point point, JComponent comp) {

    Point loc = comp.getLocation();

    loc.x += comp.getWidth() / 2;
    loc.y += comp.getHeight() / 2;

    double xdif = Math.abs(loc.x - point.x);
    double ydif = Math.abs(loc.y - point.y);

    return Math.sqrt((xdif * xdif) + (ydif * ydif));
}

This returns the hypotenuse of a triangle as a measurement in pixels, which means if the point you give it (like cursor coordinates) is at a diagonal it will give you the useful distance.

Point.distance will do something like this.


I've noticed this old answer of mine has gotten quite a few views, so here is a better way to do the above (but doesn't really show the math):

public static double distance(Point p, JComponent comp) {
    Point2D.Float center =
        // note: use (0, 0) instead of (getX(), getY())
        // if the Point 'p' is in the coordinates of 'comp'
        // instead of the parent of 'comp'
        new Point2D.Float(comp.getX(), comp.getY());

    center.x += comp.getWidth() / 2f;
    center.y += comp.getHeight() / 2f;

    return center.distance(p);
}

Here's a simple example showing this kind of geometry in a Swing program:

distance example

This draws a line to wherever the mouse cursor is and displays the length of the line (which is the distance from the center of the JPanel to the cursor).

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

class DistanceExample implements Runnable {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new DistanceExample());
    }

    @Override
    public void run() {
        JLabel distanceLabel = new JLabel("--");
        MousePanel clickPanel = new MousePanel();

        Listener listener =
            new Listener(distanceLabel, clickPanel);
        clickPanel.addMouseListener(listener);
        clickPanel.addMouseMotionListener(listener);

        JPanel content = new JPanel(new BorderLayout());
        content.setBackground(Color.white);
        content.add(distanceLabel, BorderLayout.NORTH);
        content.add(clickPanel, BorderLayout.CENTER);

        JFrame frame = new JFrame();
        frame.setContentPane(content);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    static class MousePanel extends JPanel {
        Point2D.Float mousePos;

        MousePanel() {
            setOpaque(false);
        }

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

            if (mousePos != null) {
                g.setColor(Color.red);
                Point2D.Float center = centerOf(this);
                g.drawLine(Math.round(center.x),
                           Math.round(center.y),
                           Math.round(mousePos.x),
                           Math.round(mousePos.y));
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(100, 100);
        }
    }

    static class Listener extends MouseAdapter {
        JLabel distanceLabel;
        MousePanel mousePanel;

        Listener(JLabel distanceLabel, MousePanel mousePanel) {
            this.distanceLabel = distanceLabel;
            this.mousePanel = mousePanel;
        }

        @Override
        public void mouseMoved(MouseEvent e) {
            Point2D.Float mousePos =
                new Point2D.Float(e.getX(), e.getY());

            mousePanel.mousePos = mousePos;
            mousePanel.repaint();

            double dist = distance(mousePos, mousePanel);

            distanceLabel.setText(String.format("%.2f", dist));
        }

        @Override
        public void mouseExited(MouseEvent e) {
            mousePanel.mousePos = null;
            mousePanel.repaint();

            distanceLabel.setText("--");
        }
    }

    static Point2D.Float centerOf(JComponent comp) {
        Point2D.Float center =
            new Point2D.Float((comp.getWidth() / 2f),
                              (comp.getHeight() / 2f));
        return center;
    }

    static double distance(Point2D p, JComponent comp) {
        return centerOf(comp).distance(p);
    }
}
Radiodef
  • 37,180
  • 14
  • 90
  • 125
  • I tried the getLocation method and keep getting errors related to it not being a pointer. As far as how x,y are calculated i figured if there is a standard way to define (x,y) I could just calculate the x and y values for the jbutton and compare them to the pointer. Right now I'm only using one jpanel so everything should be equivalent. – user1566796 Oct 27 '13 at 05:24
  • What do you mean by pointer? You mean you are getting a NullPointerException or are you referring to the Point? The standard way to define the coordinates depends on how you get the point. If you call getLocation on a JButton it will be a location on whatever you added the button to. It looks like you are pulling a point from a MouseEvent. If that's the case then the MouseEvent coordinates will be relative to whatever triggered the event. If you are listening to a panel then it's coordinates on the panel. If you are listening to a button then it's coordinates on the button. – Radiodef Oct 27 '13 at 05:42
  • Or do you mean what are the coordinates relative to? 0, 0 is always the top-left corner in Swing. A point coordinate on a JPanel of x = 5, y = 10 is 5 pixels in from the left of the panel and 10 pixels down from the top. Here's an SO answer with a small program that will draw a coordinate when you click on a panel if you want to see for yourself: http://stackoverflow.com/a/10811315/2891664 – Radiodef Oct 27 '13 at 05:43
  • I added a method that I think will do what you are wanting and also shows you how to calculate this without Point.distance. – Radiodef Oct 27 '13 at 06:04
  • 1
    Also consider `Math.hypot()`. – trashgod Oct 27 '13 at 07:42
  • @trashgod Yeah true there is a method for that although since the OP asked about calculations the above method is how to DIY the whole thing. (Though I'm still not clear on what aspect they were interested in particularly.) – Radiodef Oct 27 '13 at 08:19
  • My JButtons are places by FlowLayout and Im trying to find their x and y coordinates so I can place them their when I set my layout to null, but the method you described keeps returning the top left corner as 0,0 but they are not there. Tips? – Ungeheuer Jun 08 '15 at 02:02
  • @JohnnyCoder See if my edit helps you out, otherwise you should probably ask a new question. You can provide a link to this one if it provides context. – Radiodef Jun 08 '15 at 02:44
1

Something like this?:

JButton b = new JButton();
b.getAlignmentX();
b.getAlignmentY();

You can also use this:

Rectangle r = b.getBounds(); // The bounds specify this component's width, height, 
                             // and location relative to its parent.
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73