CIS-257 Home:

Custom 2D rendering with Graphics object

  1. Introduction
  2. Getting Started
  3. Project setup, step-by step


Getting Started

Project setup, step-by step

  1. Create new NetBeans Java Application project.

  2. In the project tree view, right-click "Source Packages" and select New -> JPanel form...

  3. The file is added to the project and opens in the design view. Switch to the source view of and paste paintComponent method after the class constructor:

    public class DrawingBox2D extends javax.swing.JPanel {
         * Creates new form DrawingBox2D
        public DrawingBox2D() {
        public void paintComponent( Graphics graph ) {
            // Our own 2D rendering starts here:
            graph.setColor( Color.RED );
            graph.fillRect( 10, 20, 20, 40 );
            graph.setColor( Color.BLUE );
            graph.drawString( "Hello!", 35, 45 );
            graph.drawLine( 100, 100, 80, 80 );
            int oldx = 0;
            int oldy = 0;
            for ( int x = 0; x < 360; ++x ) {
                int y = (int)( -sin( Math.toRadians(x) ) * 50 ) + 100;
                graph.drawLine( oldx, oldy, x, y );
                oldx = x;
                oldy = y;
    }//class DrawingBox2D
  4. For the above code to compile, we also need a few imports:

        import java.awt.Color;
        import java.awt.Graphics;
        import static java.lang.Math.*;
  5. In the project tree view, right-click on the drawingDemo and select New -> JFrame form... and name it FrameDemo2D

  6. The file is added to the project and opens in the design view.

  7. Select a Panel component from the palette Swing Containers category.

  8. Place the component on the JFrame form and resize it to fit the form.

  9. In the Properties sheet, switch to Code tab and rename the panel component as "pnlDrawingBoard".

  10. Right-click on the panel component in Design view and select the Customize code... option.

  11. Select custom creation in the drop-down list for the Initialization code

  12. Type in

        pnlDrawingBoard = new DrawingBox2D();

    and click OK. This custom code is placed within the GUI Builder's guarded blocks of code, which remain read-only in the regular NetBeans source editor.

  13. Set window title for FrameDemo2D as "2D Graphics Demo" in the title field of the Properties sheet. Alternatively, this can be added to the FrameDemo2D constructor:

         * Creates new form FrameDemo2D
        public FrameDemo2D() {
            setTitle( "2D Graphics Demo" );
  14. Compile and run the application. First time NetBeans will ask for the main method, you need to confirm its location in drawingDemo.FrameDemo2D class. You should get a result similar to this:

      2D Graphics Demo

  15. Now you have a window form with container that hosts your drawings. Use online tutorials to learn more about 2D graphics rendering.