awt

Drawing components example

With this tutorial we shall show you how to draw simple shapes in a Java Desktop Application. This is a very important step when designing your own graphics for your App

Basically, all you have to do in order to draw shapes in a Java application is:

  • Create a new Frame.
  • Create a class tha extends Component class and override the paint method.
  • Use Graphics2D.drawOval to draw an oval shape in the screen

 
 
Let’s see the code snippet that follows:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.javacodegeeks.snippets.desktop;
 
import java.awt.Component;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
 
public class DrawingComponentsExample {
 
  public static void main(String[] args) {
 
// Create a frame
 
Frame frame = new Frame();
 
// Add a component with a custom paint method
 
frame.add(new CustomPaintComponent());
 
// Display the frame
 
int frameWidth = 300;
 
int frameHeight = 300;
 
frame.setSize(frameWidth, frameHeight);
 
frame.setVisible(true);
 
  }
 
 /**
  * To draw on the screen, it is first necessary to subclass a Component
  * and override its paint() method. The paint() method is automatically called
  * by the windowing system whenever component's area needs to be repainted.
  */
  static class CustomPaintComponent extends Component {
 
public void paint(Graphics g) {
 
  // Retrieve the graphics context; this object is used to paint shapes
 
  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;
 
   /**
    * The coordinate system of a graphics context is such that the origin is at the
    * northwest corner and x-axis increases toward the right while the y-axis increases
    * toward the bottom.
    */
 
  g2d.drawOval(x, y, width, height);
 
}
 
  }
}

 
This was an example on how to draw components.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button