January 06, 2010

Java Graphics Example

« OpenJDK or Java Sun JDK on Ubuntu | Main | Useful Java tools »

The Graphics API is the fundament of all drawing operations on different graphics devices. The Graphics Java class represents the base class. Furthermore Graphics2D class, which is a subclass, provides extended functions (e.g. Antialiasing,...). All Swing UI components are drawn by the Java Graphics API.

The following example describes a basic usage:

public class GraphicsExample extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(
           RenderingHints.KEY_ANTIALIASING,                
           RenderingHints.VALUE_ANTIALIAS_ON);
        //set color to black
        g.setColor(Color.BLACK);
        //draw a rectangle
        g.drawRect(10, 10, 200, 200);
        //draw random circles
        for (int i = 0; i < 20; i++) {
          //set random color
          g.setColor(new Color((int) (Math.random() * 255),  
                               (int) (Math.random() * 255), 
                               (int) (Math.random() * 255)));
          g.fillOval(20 + (int) (Math.random() * 180), 
                     20 + (int) (Math.random() * 180), 5, 5);
        }
        //set color to black
        g.setColor(Color.RED);
        //draw a string
        g.drawString("developers-blog.org", 20, 20);
    }
}

Regards,
Rafael Sobek

Technorati Tags:

Posted by rafael.sobek at 11:01 PM in Java

 

[Trackback URL for this entry]

Pingback: Java Graphics Example Contact at Fr, 8 Jan 8:35 AM

Java Graphics Example
Topic: Java Graphics Example . Originally posted here:  Java Graphics Example Tags:

Pingback: Java Graphics Example | Programming News Station at Fr, 8 Jan 9:02 AM

Java Graphics Example
Blog - Programming Languages , Technologies and Visions. Topics: Visions, Architecture Issues, Programming Languages , .. Link: Java Graphics

Your comment:

(not displayed)
 
 
 

Live Comment Preview:

 
« January »
SunMonTueWedThuFriSat
     12
3456789
10111213141516
17181920212223
24252627282930
31