dcsimg
September 27, 2016
Hot Topics:

Using Graphics in JavaFX

  • March 9, 2015
  • By Manoj Debnath
  • Send Email »
  • More Articles »

JavaFX is built primarily to create and deliver rich Internet applications (RIAs) uniformly, across a variegated platform. Apart from its core utility, JavaFX is bundled with a set of APIs that not only support basic graphics programming but also some of the high-level 3D APIs as a part of the core SDK. The ease and simplicity of graphics programming with JavaFX is remarkable when compared with some of the stalwarts in this arena, such as the Java3D library. Because JavaFX is focused on an UI development, it provides some excellent features from the ground up in the graphics arena in particular. Let's explore some of its features.

JavaFX from the Ground Up

Before delving into code, we must understand some of the basic packages and classes in the SDK API class hierarchy. There are a few common classes, interplaying a crucial role and are the basis of kickstarting a graphics code environment. They can be better understood, I believe, if we draw an analogy. Let's create one as we go along.

The javafx.stage package contains the following:

  • A Stage class, which is a top-level UI container. Imagine it as the theatrical stage of the drama called graphics programming.
  • A Screen class, which represents display parameters such as size of the stage, resolution, and so forth.

The javafx.scene package (mostly used) contains these items:

  • A Scene class, which is the second-level container where the act takes place. It is similar to a scene of the drama in action or an act in motion.
  • A Node class is an abstract base class for all the graphical nodes in JavaFX, such as text, images, media, shapes, and so on. They are the actors.
  • A Group class is the subclass of Node, whose purpose is to group several node objects in to a single act.
  • A Canvas class is basically a Node subclass which provides an API to draw shapes using a set of graphics commands. The advantage of Canvas is that we can obtain its GraphicsContext and invoke drawing operations to render custom shapes onscreen.

Now, let's rephrase the analogy: The abstraction drama (graphics programming) is defined by several actors (Nodes), clubbed for interaction (Group) according to the script (Scene), dramatised on a stage (Stage), where our viewpoint (Screen) is defined by the angle/distance of the stage from the gallery.

Observe in the following code how actors (Node objects: Line and Text objects) are grouped (as a Group with children) in a scene (Scene object) and displayed in a stage (Stage object). Application.launch executes the start method implicitly and the drama is complete.

//...import statements

public class BareBoneGraphics extends Application{

   public static void main(String[] args) {
      Application.launch(args);
   }

   @Override
   public void start(Stage primaryStage) throws Exception {
      primaryStage.setTitle("Graphics in JavaFX");
      Group root=new Group();
      Scene scene=new Scene(root,300,250, Color.WHITE);

      root.getChildren().add(new Text(scene.getWidth()/2,
         scene.getHeight()/2,"Graphics is Fun"));
      root.getChildren().add(new Line(0, 5, scene.getWidth(), 5));
      root.getChildren().add(new Line(5, 0, 5, scene.getHeight()));

      primaryStage.setScene(scene);
      primaryStage.show();
   }
}

Listing 1: A barebone JavaFX graphics program

Working with Text

Text rendering is one of the common aspects when we play with graphics. We can apply several parameters to display text in a scene with a variation of font, color, stroke, fill, and rotate, and provide some effects such as shadow and the like. The following code draws text with the help of a concrete Node class, Text. The characters are displayed randomly with random rotation. Another Text object is displayed with a shadow effect.

//...import statements

public class RenderingText extends Application {

   public static void main(String[] args) {
      Application.launch(args);
   }

   @Override
   public void start(Stage primaryStage) throws Exception {
      primaryStage.setTitle("Graphics in JavaFX");
      Group root = new Group();
      Scene scene = new Scene(root, 650, 450, Color.WHITE);

      Random random = new Random(System.currentTimeMillis());
      for (int i = 0; i < 500; i++) {
         Text text = new Text(random.nextInt((int)
            scene.getWidth()),
         random.nextInt((int) scene.getHeight()),
         new Character((char)random.nextInt(255)).toString());
         text.setFont(Font.font("Serif", random.nextInt(30)));
         text.setFill(Color.rgb(random.nextInt(255),
         random.nextInt(255), random.nextInt(255), 0.5));
         root.getChildren().add(text);
      }

      Text text2 = new Text(60,
         scene.getHeight() / 2, "Graphics is Fun!");
      text2.setFont(Font.font("Serif", FontWeight.EXTRA_BOLD,
         FontPosture.REGULAR, 60));
      text2.setFill(Color.RED);
      text2.setFontSmoothingType(FontSmoothingType.LCD);
      DropShadow shadow = new DropShadow();
      shadow.setOffsetX(2.0f);
      shadow.setOffsetY(2.0f);
      shadow.setColor(Color.BLACK);
      shadow.setRadius(7);
      text2.setEffect(shadow);
      text2.setStroke(Color.DARKRED);
      root.getChildren().add(text2);

      primaryStage.setScene(scene);
       primaryStage.show();
   }
}

Listing 2: Manipulating text rendering in a scene

JavaFX1
Figure 1: Output of Listing 2

Working with Shapes

JavaFX provides an API to draw both 2D and 3D shapes. 3D shapes are a bit more complex, where concepts such as projection, camera angle, different types of light, and shading techniques come into play. Let us put that aside for now and concentrate on how we can manipulate 2D shapes. The basic 2D shapes can be used to draw more complex ones when used appropriately.

In the following example, Canvas is used as the basic drawing container. Observe how easy it is to manipulate shapes with the help of the GraphicsContext object.

public class DrawingShapes extends Application {

   public static void main(String[] args) {
      Application.launch(args);
   }

   @Override
   public void start(Stage primaryStage) throws Exception {
      primaryStage.setTitle("Graphics in JavaFX");
      Group root = new Group();
      Canvas canvas = new Canvas(650, 600);
      GraphicsContext gc = canvas.getGraphicsContext2D();
      draw2DShapes(gc);
      root.getChildren().add(canvas);
      primaryStage.setScene(new Scene(root));
      primaryStage.show();

   }

   private void draw2DShapes(GraphicsContext gc) {
      double width = gc.getCanvas().getWidth();
      double height = gc.getCanvas().getHeight();

      Random random = new Random(System.currentTimeMillis());

      gc.setFill(Color.rgb(random.nextInt(255), random.nextInt(255),
         random.nextInt(255), 0.9));
      gc.translate(width / 2, height / 2);

      for (int i = 0; i < 60; i++) {
         gc.rotate(6.0);
         gc.setFill(Color.rgb(random.nextInt(255), random.nextInt(255),
         random.nextInt(255), 0.9));
         gc.fillOval(10, 60, 30, 30);
         random.nextInt(255),
         random.nextInt(255), 0.9));
         gc.strokeOval(60, 60, 30, 30);
         gc.setFill(Color.rgb(random.nextInt(255), random.nextInt(255),
         random.nextInt(255), 0.9));
         gc.fillRoundRect(110, 60, 30, 30, 10, 10);
         gc.setFill(Color.rgb(random.nextInt(255), random.nextInt(255),
         random.nextInt(255), 0.9));
         gc.fillPolygon(
         new double[] { 105, 117, 159, 123, 133, 105, 77, 87,51, 93 },
         new double[] { 150, 186, 186, 204, 246, 222, 246,204, 186, 186 }, 10);
      }
   }
}

Listing 3: Manipulating 2D shapes with GraphicsContext in a Canvas

JavaFX2
Figure 2: Output of Listing 3

Conclusion

If you intend to unite both the world of GUI programming with graphics and animation, JavaFX is the right platform. Apart from its business utility, graphics programming is always fun in any platform or language. The thing that matters is the determinant of how steep the learning curve is. JavaFX undoubtedly provides a simple and intuitive API to work with, making the learning curve almost flat. A beginner to intermediate Java programmer with a little knowledge of computer graphics can do amazing things in JavaFX. Last but not least, with the inclusion of 3D APIs, JavaFX now has another feather on its hat; Kudos! to the FX team. This article merely scratched the surface; we'll explore more in future articles like this. Stay tuned.


Tags: Java, RIA, JavaFX, SDK, graphics, text rendering




Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date
Rocket Fuel