Draw using Alpha example

In this example we are going to see how to draw an image with Alpha enabled. The notion of Alpha is quite famous on the graphics world. This will help you to make sharper graphics and make your images look very clear and avoid pixelation.

In short, in order to enable antialiasing in your drawing, you should:

  • Create a class tha extends Component and override paint method.
  • Use AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha) to set the Alpha effect.

Let’s see the code snippet that follows:

package com.javacodegeeks.snippets.desktop;

import java.awt.AlphaComposite;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;

public class AlphaDrawing {

  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);



  * 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;

     * 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.

    int x = 0;

    int y = 0;

    int width = getSize().width-1;

    int height = getSize().height-1;

    // Draw foreground...

    // Draw an oval that fills half window

    g2d.fillOval(width/4, height/4, width/2, height/2);

    // Draw background...

    // Set alpha.  0.0f is 100% transparent and 1.0f is 100% opaque.

    float alpha = .3f;

    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));

    // Draw an oval that fills the window

    g2d.fillOval(x, y, width, height);




This was an example on how to draw using Alpha effect.

Ilias Tsagklis

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

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

Inline Feedbacks
View all comments
Back to top button