简体   繁体   English

如何获取JButton的(x,y)坐标

[英]How to get the (x,y) coordinates of JButton

Is there a method to get coordinates in the (x,y) format for a Jbutton similar to the pt.distance() method. 是否有一种方法类似于pt.distance()方法来获取Jbutton的(x,y)格式的坐标。 The jbutton utilizes setLayout(null) and setBounds(x,y,0,0). jbutton使用setLayout(null)和setBounds(x,y,0,0)。 How would I compare the results of a pt.distance() and Jbutton(x,y)? 我如何比较pt.distance()和Jbutton(x,y)的结果?

Lastly, how is (x,y) calculated? 最后,如何计算(x,y)?

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

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? Howabout getLocation ,它返回组件在其父组件上的坐标,或者getLocationOnScreen ,它返回组件在显示器上的坐标?


Your second question about how x and y are calculated, I'm not sure what you mean by 'calculated'. 关于x和y是如何计算的第二个问题,我不确定“计算”是什么意思。 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 ). 通常,要么是父组件(例如JButton所在的JPanel ),要么是屏幕上的某个位置(例如JFrame会返回getLocation )。

A method like Point.distance will subtract the two coordinates' x and y values and tell you the difference. 类似Point.distance的方法将减去两个坐标的x和y值,并告诉您差异。 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 : 例如,下面的方法将返回一个点到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. Point.distance将执行以下操作。


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: 这是一个简单的示例,在Swing程序中显示了这种几何形状:

距离示例

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). 这会在鼠标光标所在的位置绘制一条线,并显示该线的长度(这是从JPanel中心到光标的距离)。

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

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.

If by pt.distance() , you are referring to the Point2D.distance() method then you could proceed like this: 如果通过pt.distance()引用了Point2D.distance()方法,则可以这样进行:

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. 然后,该Point包含按钮的x和y坐标。 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. 但是,如果您使用的是布局,则父级的LayoutManager负责计算值。

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. JButton上调用setLayout(null)不会让您设置按钮的坐标,而只能是它的孩子。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM