FahmidasClassroom

Learn by easy steps

Graphics

The tutorial will help you to get the basic knowledge of creating graphics application using Java GUI. The ways of drawing a simple line and a rounded rectangle have been shown here. Follow the steps properly to know the uses of graphic module of java.

Step-1:

Create a project named GraphicsApp and add a class with a JFrame with the name, Graphics.

Step-2:

Import the following modules require by the class.

import java.awt.*;
import java.awt.geom.*;

Step-3:

Add a panel and two buttons in the form. Set the text of the first button to ‘Draw Line‘ and the second button to ‘Draw Rectangle‘.

Step-4:

Add the following class variables.

boolean lineThere = false;
boolean recThere = false;

Step-5:

Double clicks on the first button and add the following code to draw a line using Graphics2D class.

        // toggle button text property
        if (jButton1.getText().equals("Draw Line"))
        {
            jButton1.setText("Clear Line");
            lineThere = true;
        }
        else
        {
            jButton1.setText("Draw Line");
            lineThere = false;
        }
        Graphics2D g2D = (Graphics2D) jPanel1.getGraphics();
        Line2D.Double myLine = new Line2D.Double(0, 0, jPanel1.getWidth(), jPanel1.getHeight());

        if (lineThere)
            g2D.setPaint(Color.GREEN);
        else
            g2D.setPaint(jPanel1.getBackground());

        g2D.draw(myLine);
        g2D.dispose();

Step-6:

Double clicks on the second button and add the following code to draw a rectangle using Graphics2D class.

        Graphics2D g2D = (Graphics2D) jPanel1.getGraphics();
        

        // toggle button text property
        if (jButton2.getText().equals("Draw Rectangle"))
        {
            jButton2.setText("Clear Rectangle");
            recThere = true;
        }
        else
        {
            jButton2.setText("Draw Rectangle");
            recThere = false;
        }
        if (recThere)
            g2D.setPaint(Color.BLUE);
        else
            g2D.setPaint(jPanel1.getBackground());
        
        g2D.drawRoundRect(50, 30, 250, 150, 50, 30);
        g2D.dispose();

Step-7:

Run the application now to check the output.