Building 2-D Graphics Applications Using Java and SVG

Building 2-D Graphics Applications Using Java and SVG

s Web applications become more sophisticated, developers increasingly need to be able to incorporate dynamic graphics and animation. Unfortunately, Web browsers were originally designed to display static HTML; displaying dynamic or animated content has always been a problem in Web applications.

Nevertheless, solutions exist. One way to display dynamic content is to use Scalable Vector Graphics (SVG), a fairly recent (and still evolving) standard pioneered by Adobe, Sun Microsystems, Apple, IBM, and Kodak. SVG is basically an XML-based representation of graphical commands, used to define complex shapes such as Bezier curves. At SVG’s heart lies the world of vector-based mathematics, hence the name. The beauty of this technology is its minuscule bandwidth consumption as compared to alternatives such as dynamic jpeg file generation using Java and other graphic APIs. SVG also rivals Flash, by providing high-quality panning and zooming.

SVG can be displayed in common Web browsers, although (depending on the browser version) doing so may require a free downloadable SVG plugin from Adobe, called SVG viewer.

Author’s Note: Although other SVG viewers are available, none are even close rivals to the Adobe viewer.

Another great advantage of SVG is that you can integrate it with Java easily. In this article, you’ll see how simple it is to render dynamic graphics for display in Web browsers using SVG with JSPs by exploring how to generate a Pareto chart in SVG.

What You Need
Tomcat, and Adobe’s free SVG Viewer. Even if you’re not planning to work with the sample project, you’ll need to install the viewer to be able to view the SVG examples in this article.

Sample Project Overview

 
Figure 1. Default View of Logo.svg: This SVG file showcases curves, rectangles, text on a path, and color animation.

The sample project for this article uses a Web-based UI to get user input which it then processes to construct a Pareto chart. Kerri Simon, in this article, writes: “A Pareto chart is used to graphically summarize and display the relative importance of the differences between groups of data.” When the user clicks a “Generate” button on the UI, a JSP page renders the SVG for the chart dynamically. Using similar processing techniques, you can build any type of chart or 2-D image.

If you’re not familiar with SVG, it’s worth starting by viewing a simple SVG file. Install the Adobe SVG viewer, download the sample code, unzip it, and open the logo.svg file in your browser. You’ll see the display shown in Figure 1.

Author’s Note: Based on your browser’s security settings, you may need to give the browser permission to open the SVG. This code has been tested on IE5.5 and above, and on Mozilla Firefox 1.0.4, with the SVG viewer plugin from Adobe installed.

 
Figure 2. This figure shows the logo.svg file after a user has zoomed into the image using the features added to the browser’s context menu by the SVG plugin.

While Figure 1 shows the default view of the logo.svg file, Figure 2 shows a zoomed view. Note that you get the zoom feature by default?you don’t have to add any special code to the SVG file to provide zooming features.

A Laconic SVG Tutorial
Now that you’ve seen some rendered SVG, here’s how it works. The simplest way to create SVG files is with an SVG editor. There are quite a few SVG editors available today; in my opinion the best is Adobe Go Live. Text in SVG is both selectable and searchable, and can be displayed in any direction?which makes SVG a good choice for displaying text in non-Romanic languages such as Chinese, Japanese, or Arabic. After you familiarize yourself with the viewer plugin features (be sure to explore the right-click menu while viewing the SVG), here’s the code, so you can see how simple it is to read and relate the SVG code to the rendered version.

The quickest way to understand the code is to walk through it. I’ve added extensive comments to the SVG code below that describe the purpose of the various SVG-specific elements:

                                                                                                                              SVG Example                                            SVG                                Java, XML, JSP                                        DevX                           

You can see from the preceding code that SVG is an XML vocabulary. You can change or animate any SVG element easily by making alterations to the base XML file. Because you can draw shapes, add overlay text, lines, and other graphic shapes easily, SVG is an excellent candidate for Web-based mapping and directions applications.

Generating the Dynamic Chart
Now that you’ve seen the output from the application, the more interesting part is how you generate the SVG from a JSP. For brevity and to stick closely to the concept, I embedded the business logic in the SVGController servlet’s service method, rather than using a separate model layer. The application shows how to integrate SVG into the UI generated by the JSP. You can easily extend the same idea to a J2EE app using EJBs.

The application is composed of two JSPs and one servlet as described in the following list:

  • paretoInput.jsp?This creates the UI in which users enter values that affect the generation of the Pareto chart.
  •  
    Figure 3. Input Form: This initial page for the Web application lets users enter parameters for the Pareto chart generation.
  • SVGController.java?Extracts the input values from the submitted form, and processes them to form meaningful information with which to construct the Pareto chart. It then forwards the request to paretoOutput.jsp
  • paretoOutput.jsp?This dynamically outputs the Pareto chart and sets the content type to “SVG.”

To install and run the downloadable sample code, follow these steps. You can use any application server, but the following steps assume you’re running Tomcat.

  1. Create a new Web application called svg_j2ee, or use the war file provided in the sample code.
  2. Copy the source files paretoInput.jsp, SVG Controller and paretoOutput.jsp into the root application folder (svg_j2ee). Alternatively, you can just deploy the war file in your server.
  3. Start the server and browse to http://localhost:8080/pareto/. You’ll see a page similar to Figure 3.
  4. Fill in the input values or accept the default values.
  5. Click the “Generate” button. The server generates the chart and the browser opens it in a new window as shown in Figure 4.
 
Figure 4. Generated Pareto Chart: The paretoOutput.jsp file generates the chart dynamically, based on input values entered by the user.

A “fat rabbit” is a term used with Pareto charts to identify the root cause of an analysis. Generally it’s the block that is fatter than the rest (in this case, the first one in the chart). In this application, you can choose a different fat rabbit by clicking it with the mouse, which changes the highlighting.

Sample Application Flow
The code is simple and contains comments that should help clarify it. Here’s how the application flows through the three pages.

The application first runs the paretoInput.jsp file, which displays the input UI, asking users to enter parameters used to generate the Pareto chart. This is a standard JSP, with no reference to any SVG; it simply grabs the inputs and passes them on to the SVGController servlet for processing.

The SVGController.java servlet’s service method extracts the request parameters?the headings and values that affect the SVG rendering of the chart. It stuffs these into two vectors, sorts them based on the values, and generates helper vectors for paretoOutput.jsp, that provide percentage and cumulative percentage for graph generation. It then redirects the request, passing all the information required to construct the graph to paretoOutput.jsp as request attributes.

ParetoOutput.jsp sets the content type to “image/svg+xml” to let the browser know that the response content is an SVG file. If the response contains any content that doesn’t adhere to the SVG specification, the SVG plugin will throw an error. Next, it defines the height and width of the SVG display area. The rest of the code is self-explanatory. It is an amalgamation of JSP tags and SVG similar to the code you saw in the logo.svg file on the previous page. The file uses Java variables?passed in just as they are in any JSP?to define the chart values. The code uses those values to generate the Pareto.

It is worth mentioning that you can generate SVG dynamically using other methods such as XSLT. The design requirements of the project should drive your choice of technology. For example, if the application involves transforming XML on the server side for data exchange or for reports then the XSLT approach would make sense, whereas applications without such needs might benefit from the more direct approach described in this article. It’s also worth noting that while this sample application generates a simple chart, SVG is robust enough for use in heavy 2-D graphics applications such as the printed circuit board industry. However, at this stage, SVG’s 3-D capabilities are still somewhat limited.

SVG technology is already mature enough that there are a few books available?and there’s plenty of information on the Web if you want to learn more. The XML representation of SVG opens numerous opportunities for integrating other XML-based technologies. For example, you can use XML-based frameworks such as XUI in conjunction with SVG to provide state-of-the-art visual and interactive capabilities to your Web applications.

devx-admin

devx-admin

Share the Post:
Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India,

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1