«Back to Home

Core Java

Topics

Display Graphics In Swing Java

Display Graphics in Swing
 
In Java, java.awt.Graphics class gives many methods for the graphics programming.
 
Methods of Graphics class

public abstract void drawString(String str, int x, int y)

This method is used to draw the specific string.
 
public void drawRect(int x, int y, int width, int height)

This method is used to draw a rectangle with the particular width and height.
 
public abstract void fillRect(int x, int y, int width, int height)

This method is used to fill rectangle with the default color, particular width and height.
 
public abstract void drawOval(int x, int y, int width, int height)

This method is used to draw oval with the particular width and height.
 
public abstract void fillOval(int x, int y, int width, int height)

This method is used to fill oval with the default color, particular width and height.
 
public abstract void drawLine(int x1, int y1, int x2, int y2)

This method is used to draw the line between the points(x1, y1) and (x2, y2).
 
public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)

This method is used draw the specific image.
 
public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)

This method is used to draw a circular or elliptical arc.
 
public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)

This method is used to fill a circular or elliptical arc.
 
public abstract void setColor(Color c)

This method is used to set the graphics current color to the particular color.
 
public abstract void setFont(Font font)

This method is used to set the graphics current font to the specific font.
 
Let’s see an example of display graphics in Swing, given below.
 
Code
  1. import java.awt.*;  
  2. import javax.swing.JFrame;  
  3. public class DisplayGraphicsExample extends Canvas {  
  4.     public void paint(Graphics g) {  
  5.         g.drawString("Java Swing"5050);  
  6.         setBackground(Color.WHITE);  
  7.         g.fillRect(1204010080);  
  8.         setForeground(Color.GREEN);  
  9.     }  
  10.     public static void main(String[] args) {  
  11.         DisplayGraphicsExample dge = new DisplayGraphicsExample();  
  12.         JFrame jf = new JFrame();  
  13.         jf.add(dge);  
  14.         jf.setSize(400400);  
  15.         jf.setVisible(true);  
  16.     }  
  17. }  
53
Output

54
 
Summary

Thus, we learnt that the java.awt.Graphics class gives many methods for the graphics programming and also learnt how to display graphics in Swing Java.