LoginSignup
1
3

More than 5 years have passed since last update.

Java2Dでの画面描画

Last updated at Posted at 2015-11-26

Java3Dをやる前におさらいとしてJava2Dでの画面描画をやってみました。

描画内容
y = x の直線
r = 100 の円
上記円の楕円version の3つです。

スクリーンショット 2015-11-26 14.02.21.png

コード内容

Test.java

import javax.swing.*;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.geom.Line2D;
import java.awt.Color;

class Test1 extends JPanel{

  public static void main(String[] args){
            JFrame frame = new JFrame();

            Test1 app = new Test1();
            frame.getContentPane().add(app);

            frame.setBackground(Color.BLACK);   // windowの背景色設定
            frame.setResizable(false);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setBounds(0, 0, 400, 400);
            frame.setTitle("タイトル");
            frame.setVisible(true);
            Insets insets = frame.getInsets();  // 設定すべき値を求めるためのインスタンス化
            frame.setSize(400 + insets.left + insets.right,
                          400 + insets.top + insets.bottom); // 画面サイズ設定
          }

          public void paintComponent(Graphics g){
            Graphics2D g2 = (Graphics2D)g;
            g2.setColor(Color.white);

            g2.draw(new Line2D.Double(200,   0, 200, 400));
            g2.draw(new Line2D.Double(  0, 200, 400, 200));

            drawPoint(g2);
            drawCircle(g2);
            drawEllipse(g2);
          }

          public void drawPoint(Graphics2D g2){
              int x = 0, y = 400; 
              for(int i = 0; i < 400; i++){
                  g2.fillRect(x, y, 1, 1);
                  x += 1;
                  y -= 1;
              }
          }

          public void drawCircle(Graphics2D g2){
              double x, y, cx = 200, cy = 200, r = 100;
              for(int i = 0; i < 720; i++){
                  x = r * Math.sin(i) + cx;
                  y = r * Math.cos(i) + cy;
                  g2.draw(new Line2D.Double(x, y, x + 0.1, y + 0.1));
              }
          }

          public void drawEllipse(Graphics2D g2){
              double x, y, cx = 200, cy = 200, r = 100;
              for(int i = 0; i < 720; i++){
                  x = r * Math.sin(i) + cx;
                  y = (r * Math.cos(i)) / 2 + cy;
                  g2.draw(new Line2D.Double(x, y, x, y));
              }
          }
}

開発環境
Mac version 10.10.5

実行方法
Eclipseでインポートさせて実行してください。
コンソールで実行する場合は、

javac Test1.java
java Test1

です。

3Dに入る前に数学も勉強し直そう...

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3