2012年11月17日土曜日

Javaで等速円運動 Demo

GUIをこれから勉強しようとしている人へ


import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.Timer;

/** 球の回転(座標軸の回転) */
public class BallRoll extends JFrame {
 /* costant */
 static final int BALL_W = 100;
 static final int BALL_H = 100;
 /* field */
 private Point axis;// 軸
 private double varX;// 変動値
 private double varY;// 変動値
 private double r;// 軸からボールまでの距離
 private Timer t;// アニメーションタイマー
 private double degrees;// 角度

 /* constructor */
 public BallRoll() {
  super("Ball Roll");
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  // パソコンの画面サイズ取得
  Rectangle screen = getGraphicsConfiguration().getBounds();
  setSize(screen.width / 2, screen.width / 2);
  // windowの位置
  setLocation(screen.x + screen.width / 2 - getWidth() / 2, screen.y
    + screen.height / 2 - getHeight() / 2);
  // variable
  axis = new Point(getWidth() / 2, getHeight() / 2);
  degrees = 0;
  r = getWidth() / 2 - BALL_W - BALL_H;
  // listener
  t = new Timer(5, new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    degrees += 0.1;
    rotation(degrees);
    if (degrees >= 360)
     degrees = 0;
    repaint();
   }
  });
 }

 /* Rotation */
 public void rotation(double degrees) {
  double rad = degrees * (Math.PI / 180F);
  varX = r * Math.cos(rad) - BALL_W / 2;
  varY = r * Math.sin(rad) - BALL_H / 3;
 }

 public void paint(Graphics g) {
  super.paint(g);
  boolean xRegular = varX + BALL_W / 2 > 0;
  boolean yRegular = varY + BALL_H / 3 > 0;
  int split = 7;
  int wLength = getWidth() / split;
  int hLength = getHeight() / split;
  // 格子
  for (int i = 1; i < split; i++) {
   g.drawLine(0, hLength * i, wLength * split, hLength * i);
   g.drawLine(wLength * i, 0, wLength * i, hLength * split);
  }
  // 座標によって色を変える
  if (xRegular && yRegular)
   g.setColor(Color.RED);
  else if (xRegular && !yRegular)
   g.setColor(Color.BLUE);
  else if (!xRegular && yRegular)
   g.setColor(Color.GREEN);
  else if (!xRegular && !yRegular)
   g.setColor(Color.YELLOW);
  // 球の表示
  g.fillOval((int) (this.axis.x + varX), (int) (this.axis.y + varY),
    BALL_W, BALL_H);
  if (!t.isRunning())
   t.start();
 }

 public static void main(String[] args) {
  new BallRoll().setVisible(true);
 }
}

0 件のコメント:

コメントを投稿