Java Swing - 動的に図形を描画する

Java Swing –図形を動的に描画する例

swing-draw-shapes-3

この記事では、JPanelにランダムに図形を配置するアプリケーションを作成します。 ユーザーは、アプリケーションがサポートするさまざまな形状と描画量を選択できます。 設計上の決定として、アプリケーションは円と星を作成できます。 記事の最後に例をダウンロードして、より多くの形状、ランダムな色、ランダムなサイズなどを試すことができます。

1. サークル

コンストラクターは、直径が10pxに設定されている間、円のxおよびy座標を受け取ります。

Circle.java

package com.techfou.dynamicshapes;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;

public class Circle {

    int x, y, width, height;

    public Circle(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public void draw(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        Ellipse2D.Double circle = new Ellipse2D.Double(x, y, 10, 10);

        g2d.setColor(Color.GRAY);
        g2d.fill(circle);
    }

}

2. スター

星を描くには、GeneralPathクラスを使用します。 星を描くためにGeneralPathが従わなければならないx座標とy座標の2つの配列があります。 線は(9,0)から始まり、一連のポイントを通過して(3,18)に到達し、最後にclosePath()に到達します。これは、「開始した場所に戻る」ことを意味します。

Java’s coordinate systemを使用してこれを紙に描くと、星ができます! There is not one way to draw a star. You can play around with the numbers and make your own star, or other shapes even!

Star.java

package com.techfou.dynamicshapes;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;

public class Star {

    int x, y, width, height;

    public Star(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public void draw(Graphics g) {
        int xPoints[] = {9, 15, 0, 18, 3};
        int yPoints[] = {0, 18, 6, 6, 18};

        Graphics2D g2d = (Graphics2D) g;
        GeneralPath star = new GeneralPath();

        star.moveTo(xPoints[0] + x, yPoints[0] + y);
        for (int i = 1; i < xPoints.length; i++) {
            star.lineTo(xPoints[i] + x, yPoints[i] + y);
        }
        star.closePath();

        g2d.setColor(Color.YELLOW);
        g2d.fill(star);
    }
}

3. アプリケーション

main methodで、形状の量とタイプをユーザーに尋ねてから、JFrameを作成し、DynamicShapesクラスを呼び出してJPanelを初期化します。 JPanelを拡張するDynamicShapesクラスは、paintComponent()メソッドを介して、Listに追加された形状を描画します。 Listは、ユーザー入力に従って各形状のメソッドを呼び出すDynamicShapesクラスのコンストラクターから入力されます。

DynamicShapes.java

package com.example.dynamicshapes;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class DynamicShapes extends JPanel {

    private List shapes = new ArrayList<>();
    private Random random = new Random();

    public DynamicShapes(int i, String shape) {
        setBackground(Color.BLACK);
        setPreferredSize(new Dimension(400, 400));

        switch (shape) {
            case "Circles":
                for (int j = 0; j < i; j++) {
                    addCircle(390, 390);
                }
                break;
            case "Stars":
                for (int j = 0; j < i; j++) {
                    addStar(380, 380);
                }
                break;
            case "Both":
                int mid = i / 2;
                for (int j = 0; j < mid; j++) {
                    addCircle(390, 390);
                }
                for (int j = mid; j < i; j++) {
                    addStar(380, 380);
                }
                break;
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (Object s : shapes) {
            if (s instanceof Circle) {
                ((Circle) s).draw(g);
            } else if (s instanceof Star) {
                ((Star) s).draw(g);
            }
        }
    }

    public void addCircle(int maxX, int maxY) {
        shapes.add(new Circle(random.nextInt(maxX), random.nextInt(maxY)));
        repaint();
    }

    public void addStar(int maxX, int maxY) {
        shapes.add(new Star(random.nextInt(maxX), random.nextInt(maxY)));
        repaint();
    }

    public static void main(String[] args) {

        String shapeAmount = JOptionPane.showInputDialog(null,
                "How many shapes?", "Random Shapes...", JOptionPane.PLAIN_MESSAGE);
        int amount = Integer.parseInt(shapeAmount);

        String shapes[] = {"Stars", "Circles", "Both"};
        String shape = (String) JOptionPane.showInputDialog(null,
                "Pick the shape you want", "Random Shapes...",
                JOptionPane.PLAIN_MESSAGE, null, shapes, shapes[0]);

        JFrame frame = new JFrame();
        frame.add(new DynamicShapes(amount, shape));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }
}


出力:

「200」と入力して「OK」をクリックします

swing-draw-shapes-1

「両方」を選択し、「OK」をクリックします

swing-draw-shapes-2

結果は、JPanel内にランダムに配置された100個の星と100個の円です。

swing-draw-shapes-3

すべての組み合わせで100の形状:

swing-draw-shapes-4

ソースコードをダウンロード

ダウンロード-DrawShapesDynamically.zip(4 KB)