Drawing Program template - Java 2D Graphics

Java examples for 2D Graphics:Paint

Description

Drawing Program template

Demo Code

import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    new Main();/*from ww w  .j  a va  2  s.  com*/
  }

  Main() {
    JFrame frame = new JFrame();

    // Add a component with a custom paint method
    frame.getContentPane().add(new MyComponent());

    // Display the frame
    int frameWidth = 300;
    int frameHeight = 300;
    frame.setSize(frameWidth, frameHeight);
    frame.setVisible(true);
  }

}

class MyComponent extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;

    // Draw an oval that fills the window
    int x = 0;
    int y = 0;
    int width = getSize().width - 1;
    int height = getSize().height - 1;
    g2d.drawOval(x, y, width, height);
  }
}

Related Tutorials