プログラマメモ2 - programmer no memo2

中心点からの角度 2009/03/20


パネルの中心点とマウスをドラッグした点から角度を求めてみます。



import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class A {

public static void main(String[] args) {

JFrame frame = new JFrame() {
{
setAlwaysOnTop(true);
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

getContentPane().add(new MyPanel());

}
};
frame.setVisible(true);
}

static class MyPanel extends JComponent {

{

addMouseListener(new MouseAdapter() {

{
addMouseMotionListener(this);
}

@Override
public void mousePressed(MouseEvent e) {
mousePoint(e.getX(), e.getY());
}

@Override
public void mouseDragged(MouseEvent e) {
mousePoint(e.getX(), e.getY());
repaint();
}

});
}

Point mpoint;

void mousePoint(int x, int y) {
this.mpoint = new Point(x, y);
}

@Override
protected void paintComponent(Graphics g) {

Graphics2D g2d = (Graphics2D) g;

g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);

g2d.setColor(new Color(128, 128, 128, 128));

int cx = (int) ((getWidth() / 2));
int cy = (int) ((getHeight() / 2));

if (this.mpoint == null)
return;
g2d.drawLine(cx, cy, this.mpoint.x, this.mpoint.y);

int mx = mpoint.x - cx;
int my = mpoint.y - cy;

double degree;

if (mx == 0 && my == 0) {
degree = 0;
} else {
degree = Math.atan2(my, mx) * (180 / Math.PI);
}
g2d.setFont(new Font("Arial", Font.BOLD, 18));
g2d
.drawString("degree:" + (int) degree, this.mpoint.x,
this.mpoint.y);

g2d.drawString("角度(0~360)"
+ (int) (degree < 0 ? (180d + degree) + 180 : degree),
this.mpoint.x, this.mpoint.y + 20);
}

}

}

: