2013-10-27 6 views
0

pt.distance() 메서드와 비슷한 Jbutton의 (x, y) 형식으로 좌표를 가져 오는 방법이 있습니까? jbutton은 setLayout (null) 및 setBounds (x, y, 0,0)를 사용합니다. pt.distance() 및 Jbutton (x, y)의 결과를 어떻게 비교할 수 있습니까?JButton의 (x, y) 좌표를 얻는 방법

마지막으로 (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); 
    } 

답변

2
(가) 부모 구성 요소에 대한 구성 요소의 좌표를 반환 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); 
} 
이 마우스 커서가있는 곳으로 선을 그리고 선의 길이를 표시

distance example

:

는 여기에 스윙 프로그램에서 구조의이 종류를 보여주는 간단한 예제 (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); 
    } 
} 
+0

나는 getLocation 메소드를 시도해 포인터가 아닌 에러를 계속 발생시켰다. x, y를 계산하는 방법까지 (x, y)를 정의하는 표준 방법이 있다면 jbutton의 x와 y 값을 계산하여 포인터와 비교할 수 있다고 생각했습니다. 지금은 모든 것이 동급이어야하므로 하나의 jpanel만을 사용하고 있습니다. – user1566796

+0

포인터가 무슨 뜻입니까? NullPointerException이 발생했거나 Point를 참조하고 있습니까? 좌표를 정의하는 표준 방법은 포인트를 얻는 방법에 달려 있습니다. JButton에서 getLocation을 호출하면 버튼을 추가 한 위치의 위치가됩니다. MouseEvent에서 포인트를 가져 오는 것 같습니다. 이 경우 MouseEvent 좌표는 이벤트를 트리거 한 좌표와 관련됩니다. 패널을 듣고 있다면 패널의 좌표입니다. 버튼을 듣고 있다면 버튼의 좌표입니다. – Radiodef

+0

아니면 상대 좌표가 무엇입니까? 0, 0은 항상 Swing의 왼쪽 위 모서리입니다. x = 5, y = 10 인 JPanel의 점 좌표는 패널의 왼쪽에서 5 픽셀, 위쪽에서 10 픽셀입니다. 다음은 자신이 직접보고 싶은 경우 패널을 클릭 할 때 좌표를 그리는 작은 프로그램에 대한 SO 응답입니다. http://stackoverflow.com/a/10811315/2891664 – Radiodef

1

뭔가

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

당신은이를 사용할 수 있습니다? : :

Rectangle r = b.getBounds(); // The bounds specify this component's width, height, 
          // and location relative to its parent. 
1

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 

또는 :

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

Point 다음 버튼의 X를 포함하고 y 좌표됩니다. 레이아웃을 사용하지 않는 경우이 값은 설정 한 값이됩니다. 하지만 레이아웃을 사용하는 경우 부모의 LayoutManager이 값을 계산해야합니다.

나는 당신이하려는 것을 이해하지 못합니다. JButtonsetLayout(null)을 호출해도 단추의 좌표는 설정할 수 없으며 자식 만 있습니다. 나는 이것이 당신이 달성하려고하는 것입니다 생각 다음은 디스플레이의 구성 요소의 좌표를 반환

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

포인터가 가까워 짐에 따라 버튼이 더 빨리 움직 이도록하려고합니다. 그래서 포인터 값을 남겨 둘 필요가 있습니다. 그러나 두 값을 비교할 수있는 방법으로 버튼의 값이 필요합니다. 그런 다음 특정 범위에서 딜레이가 지연되거나 속도가 느려지는지 판단 할 수 있습니다. – user1566796

관련 문제