How do I draw various shapes in Java ? Which library should I use?

71,043

Solution 1

Sure you can do that using Swing. You may want to look into Java's Shape library for that.

Alternatively you can simply override the Component's paint method as shown below.

alt text

import javax.swing.*;
import java.awt.*;

public class ShapeTest extends JFrame{
     public ShapeTest(){
          setSize(400,400);
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setLocationRelativeTo(null);
          setVisible(true);
     }

     public static void main(String a[]){
         new ShapeTest();
     }

     public void paint(Graphics g){
          g.drawOval(40, 40, 60, 60); //FOR CIRCLE
          g.drawRect(80, 30, 200, 200); // FOR SQUARE
          g.drawRect(200, 100, 100, 200); // FOR RECT
     }
}

Solution 2

The Java2D API has what you are looking for.

Solution 3

Check out Custom Painting Approaches for a couple of ideas. The DrawOnComponent is closer to what you want. It would need to be changed to add your custom shape objects to the list.

Solution 4

GraphPanel is a simple example of an object drawing program that features moveable, resizable, colored nodes connected by edges.

Share:
71,043
Hick
Author by

Hick

Updated on April 13, 2020

Comments

  • Hick
    Hick about 4 years

    I want to write a program which can draw any type of shape that I assign to it like

    1. Circle
    2. Square
    3. Rectangle

    Which library should I use , and how do I go about it in Java ?

    I am a python coder , thus finding it difficult to cope with Java .