(가) 부모 구성 요소에 대한 구성 요소의 좌표를 반환
getLocation
Howabout
, 또는 getLocationOnScreen
?
x와 y가 어떻게 계산되는지에 대한 두 번째 질문에 '계산'이 무슨 뜻인지 확실하지 않습니다. 좌표는 상대적인 것입니다. 일반적으로 부모 구성 요소 (예 : JButton
이있는 JPanel
) 또는 화면상의 위치 (예 : getLocation
)는 JFrame
으로 반환됩니다.
Point.distance
과 같은 방법은 두 좌표 'x와 y 값을 빼서 차이점을 알려줍니다. 이것은 단지 기본 지오메트리입니다. 이것은 픽셀의 측정과 삼각형의 빗변을 반환
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));
}
의 경우 의미 예
은 여기
JButton
의 중심으로부터 점의 거리를 반환하는 방법 포인트 (커서 좌표와 같은)는 대각선에있어 유용한 거리를 제공합니다.
과 같은 기능을 수행합니다.
나는 내이 오래된 대답은 꽤 많은 의견을 얻었다 나타났습니다, 그래서 여기 위를 할 수있는 더 좋은 방법입니다 (그러나 정말 수학을 표시하지 않습니다) :
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);
}
이 마우스 커서가있는 곳으로 선을 그리고 선의 길이를 표시
:
는 여기에 스윙 프로그램에서 구조의이 종류를 보여주는 간단한 예제 (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);
}
}
나는 getLocation 메소드를 시도해 포인터가 아닌 에러를 계속 발생시켰다. x, y를 계산하는 방법까지 (x, y)를 정의하는 표준 방법이 있다면 jbutton의 x와 y 값을 계산하여 포인터와 비교할 수 있다고 생각했습니다. 지금은 모든 것이 동급이어야하므로 하나의 jpanel만을 사용하고 있습니다. – user1566796
포인터가 무슨 뜻입니까? NullPointerException이 발생했거나 Point를 참조하고 있습니까? 좌표를 정의하는 표준 방법은 포인트를 얻는 방법에 달려 있습니다. JButton에서 getLocation을 호출하면 버튼을 추가 한 위치의 위치가됩니다. MouseEvent에서 포인트를 가져 오는 것 같습니다. 이 경우 MouseEvent 좌표는 이벤트를 트리거 한 좌표와 관련됩니다. 패널을 듣고 있다면 패널의 좌표입니다. 버튼을 듣고 있다면 버튼의 좌표입니다. – Radiodef
아니면 상대 좌표가 무엇입니까? 0, 0은 항상 Swing의 왼쪽 위 모서리입니다. x = 5, y = 10 인 JPanel의 점 좌표는 패널의 왼쪽에서 5 픽셀, 위쪽에서 10 픽셀입니다. 다음은 자신이 직접보고 싶은 경우 패널을 클릭 할 때 좌표를 그리는 작은 프로그램에 대한 SO 응답입니다. http://stackoverflow.com/a/10811315/2891664 – Radiodef