import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.*; public class Test { public static void main (String[] args) { Graphics2D3 win = new Graphics2D3("Graphics2D クラス,hit"); } } class Graphics2D3 extends JFrame { /******************/ /* コンストラクタ */ /******************/ Graphics2D3(String name) { // JFrameクラスのコンストラクタ(Windowのタイトルを引き渡す) super(name); // Windowの大きさ setSize(640, 470); // Graphics2D3_MainPanel オブジェクト Dimension d = getSize(); // フレームの大きさ Graphics2D3_MainPanel pn = new Graphics2D3_MainPanel(d); // Graphics2D3_MainPanel オブジェクトの生成 getContentPane().add(pn); // Graphics2D3_MainPanel オブジェクトを ContentPane に追加 // ウィンドウを表示 setVisible(true); // イベントアダプタ addWindowListener(new WinEnd()); } /******************************/ /* 上,左,下,右の余白の設定 */ /******************************/ public Insets getInsets() { return new Insets(50, 20, 20, 20); } /************/ /* 終了処理 */ /************/ class WinEnd extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } } class Graphics2D3_MainPanel extends JPanel implements Runnable { boolean state = true; double x1, x2, y1, y2, t = 0.0, v = 20.0; Dimension d; Thread th; Rectangle rec; Ellipse2D.Double cir; boolean hit = false; Graphics2D3_MainPanel(Dimension d1) { d = d1; x1 = 0.0; x2 = d.width - 80; y1 = d.height / 2 - 40; y2 = d.height / 2 - 80; setBackground(Color.white); // 背景色の設定 th = new Thread(this); // スレッドの生成とスタート th.start(); } // スレッドの実行 public void run() { while (state) { try { th.sleep(33); } catch (InterruptedException e) {} if (hit) state = false; else { if (x1 < d.width) { t += 0.1; x1 = v * t; x2 = d.width - 80 - v * t; } else { x1 = 0; x2 = d.width - 80; t = 0; } } repaint(); } } // 描画 public void paintComponent(Graphics g) { super.paintComponent(g); // 親クラスの描画 // Graphics2Dの取得 Graphics2D g2 = (Graphics2D)g; // 塗りつぶした矩形 g2.setColor(Color.green); rec = new Rectangle((int)x1, (int)y1, 80, 80); g2.fill(rec); // 塗りつぶした円 g2.setColor(Color.red); cir = new Ellipse2D.Double(x2, y2, 80, 80); g2.fill(cir); hit = g2.hit(rec, cir, false); } }