NetBeans, Java, and JFreeChart. An introduction for the complete novice (Part 1)



Similar documents

Illustration 1: An applet showing constructed responses in an intuitive mode. Note the misprint!

Eclipse with Mac OSX Getting Started Selecting Your Workspace. Creating a Project.

Tutorial: Time Of Day Part 2 GUI Design in NetBeans

Java Software Development Kit (JDK 5.0 Update 14) Installation Step by Step Instructions

Scientific Graphing in Excel 2010

Appendix B Task 2: questionnaire and artefacts

Java is commonly used for deploying applications across a network. Compiled Java code

Designing a Graphical User Interface

Introduction to Eclipse

Tutorial 5: Developing Java applications

Eclipse installation, configuration and operation

How to Install Java onto your system

Lecture 2 Mathcad Basics

Hypercosm. Studio.

Lab 1A. Create a simple Java application using JBuilder. Part 1: make the simplest Java application Hello World 1. Start Jbuilder. 2.

Updates to Graphing with Excel

Windows XP Pro: Basics 1

Section 1: Ribbon Customization

Intermediate PowerPoint

Download and Installation Instructions. Java JDK Software for Windows

Using Eclipse to Run Java Programs

How to create PDF maps, pdf layer maps and pdf maps with attributes using ArcGIS. Lynne W Fielding, GISP Town of Westwood

Java with Eclipse: Setup & Getting Started

Building Qualtrics Surveys for EFS & ALC Course Evaluations: Step by Step Instructions

NICK COLLIER - REPAST DEVELOPMENT TEAM

Once you have obtained a username and password you must open one of the compatible web browsers and go to the following address to begin:

The goal with this tutorial is to show how to implement and use the Selenium testing framework.

DATA MINING TOOL FOR INTEGRATED COMPLAINT MANAGEMENT SYSTEM WEKA 3.6.7

A product of Byte Works, Inc. Credits Programming Mike Westerfield. Art Karen Bennett. Documentation Mike Westerfield

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

Learn how to create web enabled (browser) forms in InfoPath 2013 and publish them in SharePoint InfoPath 2013 Web Enabled (Browser) forms

Summary of important mathematical operations and formulas (from first tutorial):

Getting Started with WebSite Tonight

Virtual Office Remote Installation Guide

LAB4 Making Classes and Objects

What is a Mail Merge?

0 Introduction to Data Analysis Using an Excel Spreadsheet

Statgraphics Getting started

Adobe Acrobat 6.0 Professional

Installing Java. Table of contents

ITS Training Class Charts and PivotTables Using Excel 2007

Week 2 Practical Objects and Turtles

Importing and Exporting With SPSS for Windows 17 TUT 117

Microsoft Expression Web

Chapter 14: Links. Types of Links. 1 Chapter 14: Links

STC: Descriptive Statistics in Excel Running Descriptive and Correlational Analysis in Excel 2013

Content Author's Reference and Cookbook

Managing Files. On a PC, after you find your file, right click it and selet Rename from the pop-up menu.

Making a Web Page with Microsoft Publisher 2003

Hadoop Tutorial. General Instructions

Creating a Java application using Perfect Developer and the Java Develo...

Using Karel with Eclipse

Editors Comparison (NetBeans IDE, Eclipse, IntelliJ IDEA)

My EA Builder 1.1 User Guide

Supplement I.B: Installing and Configuring JDK 1.6

MARS STUDENT IMAGING PROJECT

Using the SAS Enterprise Guide (Version 4.2)

Appendix A Using the Java Compiler

Open a PDF document using Adobe Reader, then click on the Tools menu on the upper left hand corner.

If there is not a Data Analysis option under the DATA menu, you will need to install the Data Analysis ToolPak as an add-in for Microsoft Excel.

Data representation and analysis in Excel

NetBeans IDE Field Guide

For Introduction to Java Programming, 5E By Y. Daniel Liang

McAfee Endpoint Encryption Reporting Tool

Adobe Conversion Settings in Word. Section 508: Why comply?

Notepad++ The COMPSCI 101 Text Editor for Windows. What is a text editor? Install Python 3

The X3 Savegame Manager - v 1.i User Guide

Sample Table. Columns. Column 1 Column 2 Column 3 Row 1 Cell 1 Cell 2 Cell 3 Row 2 Cell 4 Cell 5 Cell 6 Row 3 Cell 7 Cell 8 Cell 9.

Excel Integrated Reporting

Programming with Java GUI components

Supplement I.B: Installing and Configuring JDK 1.6

Directions for Frequency Tables, Histograms, and Frequency Bar Charts

Debugging Java Applications

Chapter 4 Displaying and Describing Categorical Data

Using Word 2007 For Mail Merge

LAB 6: Code Generation with Visual Paradigm for UML and JDBC Integration

Publishing Geoprocessing Services Tutorial

Microsoft Access 2007 Introduction

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

WIRIS quizzes web services Getting started with PHP and Java

Creating tables of contents and figures in Word 2013

MS WORD 2007 (PC) Macros and Track Changes Please note the latest Macintosh version of MS Word does not have Macros.

(Least Squares Investigation)

Installing Ruby on Windows XP

Install Java Development Kit (JDK) 1.8

Right now, the latest and greatest version of Java available for download is Start with this link to find out more about it

This web-based report provides information for single funds centers. The report can be run for one funds center or multiple single funds centers.

Excel 2007 Basic knowledge

Reviewing documents with track changes in Word 2013

Smart Connection 9 Element Labels

Microsoft Publisher 2010: Web Site Publication

IDS 561 Big data analytics Assignment 1

WINDOWS LIVE MAIL FEATURES

Android Studio Application Development

Bluetooth Installation

Dealing with Data in Excel 2010

CATIA V5 Tutorials. Mechanism Design & Animation. Release 18. Nader G. Zamani. University of Windsor. Jonathan M. Weaver. University of Detroit Mercy

Spotfire v6 New Features. TIBCO Spotfire Delta Training Jumpstart

Transcription:

NetBeans, Java, and JFreeChart An introduction for the complete novice (Part 1) Carl David Carl.David@uconn.edu Introduction This set of papers consists of an introduction to JFreeChart and NetBeans as an IDE for Java programming. I attempt herein to ease the learning burden, a little, compared to the misery that I had to suffer through. We are using JDK 1.5.0_03, NetBeans 4.1 (for future work, we've gone over to 5.0), and jfreechart-1.0.0-rc1. I hope its not necessary to mention that all of these programs are free, in the public domain, and can be downloaded and installed on modern PCs. Please, if you read this and find mistakes, please e-mail me at Carl.David@uconn.edu and I will correct them. Everything you read here has been achieved created by hacking through every piece of material I can find on the WWW concerning the topics being discussed. Orginality is explicitly eschewed. Stealing code from every legal source is, a posteriori, acceptable 1. Starting a New Project To start a project, left-click File New Project. Then, after following the menus and naming the project, creating a Main application, etc., you can start coding into this Main application, and use the various build and clean functions, but if you choose to create named Applications, then, inside the project, one can right-click on the project node to get a menu, choose New, and then look for a kind of form which makes sense. In this case, I want a graphical application with swing, and with a graphical part, i.e., one which, when it comes up on the screen, I want it to have a drawing face, perhaps a menu, etc., choose Java GUI Forms Sample Forms Application. Notice that this will not be the Main application, and therefore, although F9 will compile it, Shift-F6 is needed to execute it, etc.. Perhaps it makes sense to use the Main project instead, but the method I've chosen, at least at the beginning, has been OK except for refactoring, which hasn't worked as I'd expected. 1 Plagiarize, Let no one else's work evade your eyes, Remember why the good Lord made your eyes, So don't shade your eyes, But plagiarize, plagiarize, plagiarize... Only be sure always to call it please, "research". Thank you Tom Lehrer

Before creating a new Application set up your libraries! Before starting creating applications, right-click on the project, and find the bottom entry, properties. Click here, and click on libraries, and then find the jfreechart libraries required and insert them into the classpath: Illustration 1Figure 1 (notice Libraries is highlighted, and then following the next menu s choices, locate the jar files necessary, wherever you ve placed them). Creating a new Application inside an existing Project with Graphical Interface Now, when you right-click on your project and choose New, you can get a choice included in Figure 2 (see below).

Illustration 2Figure 2 Just follow the menus from here. Just remember that there will be no Main, and therefore shift-f6 executes the current program, etc.. Just check the right-clicks on the program's name in the Project window to see your options. Example 1 Example 1 will consist of a cosine plot, in the easiest manner possible (I think). Here is my example1 code: /* * example1.java * * Created on September 22, 2005, 11:47 AM /** * * @author david import org.jfree.*; import org.jfree.data.xy.*;//needed for XYSeries, could have called directly import org.jfree.chart.*;//needed for createxylinechart import java.math.*;//needed for cosine import java.awt.image.*;//needed for Buffered Image import javax.swing.*; public class example1 extends javax.swing.jframe { /** Creates new form example1 public example1() { initcomponents(); System.out.println("After initcomponents"); y_of_x = new double[n_points]; x = new double[n_points]; XYSeries series = new XYSeries("Cos(x) versus x");

for (int i = 0;i< n_points;i++){//calculate the data to be plotted y_of_x[i] = Math.cos(i*Math.PI/180); series.add((double)i,y_of_x[i]) ;//add the computed values to the series XYDataset dataset = new XYSeriesCollection(series); JFreeChart chart = ChartFactory.createXYLineChart( "Cos(x) versus x", "x", "cos(x)", dataset, org.jfree.chart.plot.plotorientation.vertical, true, false, false); BufferedImage image = chart.createbufferedimage(400,500); jlabel1.seticon(new ImageIcon(image)); /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. // <editor-fold defaultstate="collapsed" desc=" Generated Code "> // </editor-fold> private void exitmenuitemactionperformed(java.awt.event.actionevent evt) { System.exit(0); /** * @param args the command line arguments public static void main(string args[]) { java.awt.eventqueue.invokelater(new Runnable() { public void run() { new example1().setvisible(true); ); // Variables declaration - do not modify private javax.swing.jmenuitem aboutmenuitem; private javax.swing.jmenuitem contentsmenuitem; private javax.swing.jmenuitem copymenuitem; private javax.swing.jmenuitem cutmenuitem; private javax.swing.jmenuitem deletemenuitem; private javax.swing.jmenu editmenu; private javax.swing.jmenuitem exitmenuitem; private javax.swing.jmenu filemenu; private javax.swing.jmenu helpmenu; private javax.swing.jlabel jlabel1; private javax.swing.jmenubar menubar; private javax.swing.jmenuitem openmenuitem; private javax.swing.jmenuitem pastemenuitem; private javax.swing.jmenuitem saveasmenuitem;

private javax.swing.jmenuitem savemenuitem; // End of variables declaration public static int n_points = 500; public static double[] y_of_x,x;//we will plot y(x) versus x Notice that I've highlighted code which was created by NetBeans. Also, some NetBeans generated code is hidden (folded), to allow faster traversals of one's code. Here is the folded code which has been generated using the Design button to graphically create the code for a panel inside the face of the application: private void initcomponents() { jlabel1 = new javax.swing.jlabel(); menubar = new javax.swing.jmenubar(); filemenu = new javax.swing.jmenu(); openmenuitem = new javax.swing.jmenuitem(); savemenuitem = new javax.swing.jmenuitem(); saveasmenuitem = new javax.swing.jmenuitem(); exitmenuitem = new javax.swing.jmenuitem(); editmenu = new javax.swing.jmenu(); cutmenuitem = new javax.swing.jmenuitem(); copymenuitem = new javax.swing.jmenuitem(); pastemenuitem = new javax.swing.jmenuitem(); deletemenuitem = new javax.swing.jmenuitem(); helpmenu = new javax.swing.jmenu(); contentsmenuitem = new javax.swing.jmenuitem(); aboutmenuitem = new javax.swing.jmenuitem(); setdefaultcloseoperation(javax.swing.windowconstants.exit_on_close); jlabel1.settext("<=picture"); getcontentpane().add(jlabel1, java.awt.borderlayout.center); filemenu.settext("file"); openmenuitem.settext("open"); filemenu.add(openmenuitem); savemenuitem.settext("save"); filemenu.add(savemenuitem); saveasmenuitem.settext("save As..."); filemenu.add(saveasmenuitem); exitmenuitem.settext("exit"); exitmenuitem.addactionlistener(new java.awt.event.actionlistener() { public void actionperformed(java.awt.event.actionevent evt) { exitmenuitemactionperformed(evt); ); filemenu.add(exitmenuitem); menubar.add(filemenu); editmenu.settext("edit"); cutmenuitem.settext("cut"); editmenu.add(cutmenuitem); copymenuitem.settext("copy");

editmenu.add(copymenuitem); pastemenuitem.settext("paste"); editmenu.add(pastemenuitem); deletemenuitem.settext("delete"); editmenu.add(deletemenuitem); menubar.add(editmenu); helpmenu.settext("help"); contentsmenuitem.settext("contents"); helpmenu.add(contentsmenuitem); aboutmenuitem.settext("about"); helpmenu.add(aboutmenuitem); menubar.add(helpmenu); setjmenubar(menubar); pack(); In the future this folded code will be omitted. It is generated by the system, either during initialization or during construction of the graphical interface, and can be folded out of view for easier comprehension of the program s text. To create our code, one starts with a definition (at the bottom, following the definitions induced by the NetBeans IDE): public static int n_points = 500; public static double[] y_of_x,x;//we will plot y(x) versus x thinking that we will store the plot s abscissa in a vector. It turns out to be unnecessary, but so what 2. Next, we create an instance of these variables, and attempt to create a jfreechart series instance. This fails, since we do not have jfreechart available for use yet, y_of_x = new double[n_points]; x = new double[n_points]; XYSeries series = new XYSeries("Cos(x) versus x"); so we need import org.jfree.data.xy.*;//needed for XYSeries, could have called directly or we could have written org.jfree.data.xy.xyseries explicitly. This is easier, but finding oneself inside the various folders takes some getting used to. Next, we want to generate the data. for (int i = 0;i< n_points;i++){//calculate the data to be plotted y_of_x[i] = Math.cos(i*Math.PI/180); series.add((double)i,y_of_x[i]) ;//add the computed values to the series Notice the construction of the for (){ group. Also notice that we need to add the statement import java.math.*;//needed for cosine 2 In future incarnations, we'll consolidate the code omiting the y_of_x[] vector, but it doesn;t hurt to leave it in here.

in order to achieve the use of the cosine (and other) functions 3. Next, we follow an algorithm to create out plot: XYDataset dataset = new XYSeriesCollection(series); JFreeChart chart = ChartFactory.createXYLineChart( "Cos(x) versus x", "x", "cos(x)", dataset, org.jfree.chart.plot.plotorientation.vertical, true, false, false); Finally, we display the chart in the simplest possible manner: BufferedImage image = chart.createbufferedimage(400,500); jlabel1.seticon(new ImageIcon(image)); Where did jlabel1 come from? It came from the Design tab's functioning. We picked out jlabel and then touched the center of our displayed layout, and, lo and behold, there we are, its all done. If one looks at the Properties of jlabel1, one can find its Text and edit it to what one <=picture, which makes our output just a little more professional looking than the default value. Saving one's work For protection, we now click on the source code in the Project window, copy it, and paste it back into the source folder. It is created as example1_1 which we re-factor and re-name as example1_original (or something like that). Then we can fiddle with example1 and later re-factor/re-name its future conent to example2, using the same skeleton code. Actually, this hasn't worked as I'd expected, and perhaps you can suggest an alternative scheme. Two Graphs on the Same Page For scientific work, one often needs present two (or more) graphs sharing the common ordinate but different abscissas. example2 is my choice of how to do this. /* * example2.java * * Created on September 22, 2005, 11:47 AM /** * * @author david import org.jfree.*; import org.jfree.data.xy.*;//needed for XYSeries, could have called directly import org.jfree.chart.*;//needed for createxylinechart 3 Or write java.math.cos.

import org.jfree.data.xy.xyseriescollection; import org.jfree.chart.plot.*; import org.jfree.chart.axis.*; import org.jfree.chart.renderer.xy.*; import java.math.*;//needed for cosine import java.awt.image.*;//needed for Buffered Image import javax.swing.*; import java.awt.font; public class example2 extends javax.swing.jframe { /** * Creates new form example2 public example2() { initcomponents(); System.out.println("After initcomponents"); y_of_x = new double[n_points]; x = new double[n_points]; XYSeries series1 = new XYSeries("Cos(x) versus x"); XYSeries series2 = new XYSeries("Cos^2(x) versus x"); for (int i = 0;i< n_points;i++){//calculate the data to be plotted y_of_x[i] = Math.cos(i*Math.PI/180); series1.add((double)i,y_of_x[i]) ;//add the computed values to the series series2.add((double)i,math.pow(y_of_x[i],2)) ; XYDataset dataset1 = new XYSeriesCollection(series1); XYDataset dataset2 = new XYSeriesCollection(series2); CombinedDomainXYPlot parent = new CombinedDomainXYPlot(new NumberAxis("x-angle argument")); XYItemRenderer renderer1 = new StandardXYItemRenderer(); XYItemRenderer renderer2 = new StandardXYItemRenderer(); XYPlot subplot1 = new XYPlot(dataset1,null, new NumberAxis("Cos(x)"),renderer1); NumberAxis axis1 = (NumberAxis)subplot1.getRangeAxis(); axis1.setticklabelfont(new Font("Monospaced", Font.PLAIN,7)); axis1.setlabelfont(new Font("SansSerif", Font.PLAIN,7)); axis1.setautorangeincludeszero(false); parent.add(subplot1,1); XYPlot subplot2 = new XYPlot(dataset2,null, new NumberAxis(null),renderer2); NumberAxis axis2 = (NumberAxis)subplot2.getRangeAxis(); axis2.setticklabelfont(new Font("Monospaced", Font.PLAIN,11)); axis2.setlabelfont(new Font("SansSerif", Font.PLAIN,9)); axis2.setautorangeincludeszero(false); parent.add(subplot2,1); JFreeChart chart = new JFreeChart("Cos(x) versus x", parent); BufferedImage image = chart.createbufferedimage(400,500); jlabel1.seticon(new ImageIcon(image)); /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor.

//folded code omitted private void exitmenuitemactionperformed(java.awt.event.actionevent evt) { System.exit(0); /** * @param args the command line arguments public static void main(string args[]) { java.awt.eventqueue.invokelater(new Runnable() { public void run() { new example2().setvisible(true); ); // Variables declaration - omitted // End of variables declaration public static int n_points = 500; public static double[] y_of_x,x;//we will plot y(x) versus x To see what the code is doing, we first look at the for(){ loop: for (int i = 0;i< n_points;i++){//calculate the data to be plotted y_of_x[i] = Math.cos(i*Math.PI/180); series1.add((double)i,y_of_x[i]) ;//add the computed values to the series series2.add((double)i,math.pow(y_of_x[i],2)) ; The cos(x) and cos 2 (x) are part of the java.math.* classes which can be imported or explictly coded. Next, we define two rather than one XYDataset: XYDataset dataset1 = new XYSeriesCollection(series1); XYDataset dataset2 = new XYSeriesCollection(series2); Each dataset is addresses a different function. They are going to be combined together using a new kind of plot: CombinedDomainXYPlot parent = new CombinedDomainXYPlot(new NumberAxis("x-angle argument")); Then we define a renderer for each of the datasets, e.g., XYItemRenderer renderer1 = new StandardXYItemRenderer(); Penultimately, we set up each series to be added: XYPlot subplot1 = new XYPlot(dataset1,null, new NumberAxis("Cos(x)"),renderer1); NumberAxis axis1 = (NumberAxis)subplot1.getRangeAxis(); axis1.setticklabelfont(new Font("Monospaced", Font.PLAIN,7)); axis1.setlabelfont(new Font("SansSerif", Font.PLAIN,7)); axis1.setautorangeincludeszero(false); parent.add(subplot1,1); First, we define subplot1, defining the axis label ( Cos(x) ), and associate the proper renderer which will give rise to a unique color for this particular suplot (among other things). We define this plot's axis and set up some axis properties, ending by adding the

subplot to the CombinedDomainXYPlot (parent). The weight (1) could have been omitted, or changed to have this plot bigger (or smaller) that its brother. Of course, we do the same with the second series of data points, cos 2 (x), but this time we change some properties so that we can tell what we are doing. Finally, we repeat the code from example1 to display the code. JFreeChart chart = new JFreeChart("Cos(x) versus x", parent); BufferedImage image = chart.createbufferedimage(400,500); jlabel1.seticon(new ImageIcon(image)); In the next example, we'll use a different way of displaying our graph. Adding javadocs In the NetBeans IDE, one of the great conveniences is the idea that when one types org. 4 a popup window shows up with choices for the next element, such that clicking on jfree and then adding a period yields org.jfree. with yet another popup box, etc.. These boxes are accompanied by explanatory javadocs boxes if the appropriate foreign (to NetBeans and Java) javadocs have been placed in the appropriate libraries. After some trial and error, the following worked: Illustration 3Figure 3 where a right-click on the appropriate project followed by Properties followed by Libraries allowed us to add the docs zip file, and suddenly everything worked. Since I 4 With the period at the end!

added this same zip file to the libraries under Tools, I'm not sure what's going on, and the NetBeans documentation is not too clear, but a little trial and error worked for me and will, presumably, work for you. Example2a We here change the past example to a briefer form: XYDataset dataset1 = new XYSeriesCollection(series1); XYDataset dataset2 = new XYSeriesCollection(series2); CombinedDomainXYPlot parent = new CombinedDomainXYPlot(new DateAxis("")); XYItemRenderer renderer1 = new StandardXYItemRenderer(); Notice that we've chosen a different scheme for displaying the graph, i.e., using a ChartPanel: XYItemRenderer renderer2 = new StandardXYItemRenderer(); XYPlot subplot1 = new XYPlot(dataset1,null, new NumberAxis(null),renderer1); XYPlot subplot2 = new XYPlot(dataset2,null, new NumberAxis(null),renderer2); parent.add(subplot1); parent.add(subplot2); JFreeChart chart = new JFreeChart("Cos(x) and Cos^2(x) versus x", parent); /* commented out BufferedImage image = chart.createbufferedimage(400,500); jlabel1.seticon(new ImageIcon(image)); * ChartPanel mychart = new ChartPanel(chart); this.setcontentpane(mychart); And we've finished with our introduction. Good luck.