Translate and draw rectangle - Java 2D Graphics

Java examples for 2D Graphics:Transform

Description

Translate and draw rectangle

Demo Code

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;

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

public class Opdracht2_3 extends JFrame {

  public static void main(String[] args) { // TODO Auto-generated method stub
    Opdracht2_3 opdr = new Opdracht2_3();
  }/* w  ww .  ja  va2 s  .c  o  m*/

  public Opdracht2_3() {
    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);

    JLabel statusLabel = new JLabel("Draw a Line");
    topPanel.add(statusLabel);

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

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

    setContentPane(panel);
    setVisible(true);
  }

  public class Opdracht2_3a extends JPanel {
    public Opdracht2_3a() {
      setPreferredSize(new Dimension(600, 400));
    }

    public void paintComponent(Graphics g) {
      Graphics2D g2 = (Graphics2D) g;
      g2.translate(200, 200);
      g2.drawRect(0, 0, 200, 200);
      g2.rotate(Math.PI / 4, 0, 0);
      g2.drawRect(0, 0, 200, 200);

    }
  }

}

Related Tutorials