Search code examples
javagraphicspaneldraw

Java, create and edit a Graphics Object for Panel?


I have the following task for my school in Java:

Create a GUI window with your own graphic. This graphic should be created in a separate JPanel class and drawn using the draw and fill methods of the java.awt.Graphics class (e.g. a house with a garden, a car, ...). The graphic should contain at least 5 different types of graphics (rectangle, oval, ...), at least one polygon (draw or fillPolygon (polygon p) method) and an arc (draw or fillArc method (int x, int y, int width, int height, int startAngle, int arcAngle)). The graphic should also contain at least 10 drawing elements and consist of at least 4 different colors.

But I don´t know how to use the class Graphics, so I don´t know how to create a Grahpics object and edit it. Does anyone know how to solve this? Thank you


Solution

  • You can use graphics with a JPanel;

    class exampleclass extends JPanel {
        exampleClass() {
           ...
        }
    
        @Override
        public void paintComponent(Graphics g) {
            ...your code here...
        }
    
    }
    

    For more information, look at; https://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html

    You can call paint method with, repaint();