Draw curve using GeneralPath - Java 2D Graphics

Java examples for 2D Graphics:Graphics

Description

Draw curve using GeneralPath

Demo Code


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main extends JFrame {
  public static void main(String[] args) {
    Main opdr = new Main();
  }// w ww  .  ja v  a  2s . c o m

  public Main() {
    super("line");
    setSize(600, 600);
    setTitle("2D Line");

    setDefaultCloseOperation(EXIT_ON_CLOSE);

    JPanel panel = new JPanel(new BorderLayout());
    JPanel topPanel = new JPanel(new FlowLayout());
    panel.add(topPanel, BorderLayout.NORTH);
    // panel.setBackground(Color.black);
    JLabel statusLabel = new JLabel("Draw a Line");
    topPanel.add(statusLabel);

    JPanel centerPanel = new Opdracht2_6a();
    panel.add(centerPanel, BorderLayout.CENTER);

    JPanel bottomPanel = new JPanel(new FlowLayout());
    panel.add(bottomPanel, BorderLayout.SOUTH);

    setContentPane(panel);
    setVisible(true);
  }

  public class Opdracht2_6a extends JPanel {
    private GeneralPath myShape = new GeneralPath();

    public Opdracht2_6a() {
      setPreferredSize(new Dimension(600, 600));

      myShape = new GeneralPath();
      myShape.moveTo(0f, -1f);
      myShape.curveTo(0, -1, -2.5, 0, 0, 1);
      myShape.moveTo(0f, 1f);
      myShape.quadTo(-1, 0, 0, -1);

    }

    public void paintComponent(Graphics g) {
      super.paintComponents(g);
      Graphics2D g2 = (Graphics2D) g;
      AffineTransform tr = new AffineTransform();
      tr.setToScale(100, 100);
      Shape sh = tr.createTransformedShape(myShape);
      g2.translate(300, 200);

      g2.setColor(Color.black);
      // g2.fill(sh);
      g2.draw(sh);

    }
  }

}

Related Tutorials