Gantt Chart

A free public discussion forum for JFreeDesigner, a report definition designer for JFreeReport.
Locked
suvithahez
Posts: 1
Joined: Fri Jun 01, 2007 5:15 am
Location: Chennai
Contact:

Gantt Chart

Post by suvithahez » Fri Jun 01, 2007 5:39 am

Hi,
Urgent help.I have coded and the output is getting properly .Only problem is the space between the y axis intervals. one customer has one goal and another customer has 7 goals its equally occupying the space for both the customers in the Gantt chart.Please anyone help for this .This is the following code.
package com.hsbc.ris.presentation.gi.applet;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;

import netscape.javascript.JSObject;
import java.awt.Dimension;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartMouseEvent;
import org.jfree.chart.ChartMouseListener;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.AxisSpace;
import org.jfree.chart.axis.CategoryAnchor;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.DateTickUnit;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.entity.CategoryItemEntity;
import org.jfree.chart.labels.CategoryItemLabelGenerator;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.IntervalMarker;
import org.jfree.chart.renderer.category.GanttRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.IntervalCategoryDataset;
import org.jfree.data.gantt.Task;
import org.jfree.data.gantt.TaskSeries;
import org.jfree.data.gantt.TaskSeriesCollection;
import org.jfree.ui.Layer;
import org.jfree.ui.RectangleAnchor;
import org.jfree.ui.TextAnchor;

public class LifeCalendarAppletChart implements ChartMouseListener, ActionListener, CategoryItemLabelGenerator {
public static final int LC_WIDTH = 700;
private static final int LC_MIN_HEIGHT = 2000;
private static final int LC_MIN_PERSONS = 5;

private JPanel chart = null;
public List customerList = new ArrayList();
public List goalList = new ArrayList();
private String lcCustName = null;
private String lcGaolDesc = null;
private String lcStartYr = null;
private String lcEndYr = null;
private String lcGoalId = null;
private String lcGoalType = null;
private String graphProtectionYear = null;
private String graphXLimit = null;
private String mouseClickedGoalName = null;
private String localeString = null;
private String custDOB = null;
String[] lcGoalIdArr = null;
String[] lcGoalTypeArr = null;
String mouseFunctions = null;
private Calendar calendar = new java.util.GregorianCalendar();
JPopupMenu popupMenu;
JSObject jsObject;
CategoryItemEntity entity;
Locale locale;
CategoryPlot plot = null;

int nCust = 1;
HashMap custGoals = new HashMap();
HashMap custGoalIds = new HashMap();
HashMap custGoalTypes = new HashMap();
int goalListCount = 0;
String goalId = "";
String selectedGoalType = "";

public JPanel getChart() {
return this.chart;
}

public LifeCalendarAppletChart(String title, String lcCustName, String lcGaolDesc, String lcStartYr, String lcEndYr, String graphProtectionYear, String graphXLimit, JSObject jsObject, String lcGoalId, String lcGoalType, String localeString,String mouseFunctions, String custDOB, int chartWidth, int chartHeight) {
this.lcCustName = lcCustName;
this.lcGaolDesc = lcGaolDesc;
this.lcStartYr = lcStartYr;
this.lcEndYr = lcEndYr;
this.lcGoalId = lcGoalId;
this.graphProtectionYear = graphProtectionYear;
this.graphXLimit = graphXLimit;
this.jsObject = jsObject;
this.lcGoalType = lcGoalType;
this.localeString = localeString;
this.mouseFunctions = mouseFunctions;
this.custDOB = custDOB;

String language = localeString.substring(0,2);
String country = localeString.substring(3,5);
locale =new Locale(language,country);

JPanel chartPanel = createDemoPanel();
int numGoals = lcGaolDesc.split("~").length;
if (numGoals <= 25) {
chartPanel.setMaximumSize(new java.awt.Dimension(LC_WIDTH, LC_MIN_HEIGHT));
} else {
chartPanel.setMaximumSize(new java.awt.Dimension(LC_WIDTH, LC_MIN_HEIGHT + numGoals * 100));
}

this.chart = chartPanel;
}

/**
* Creates a sample dataset for a Gantt chart.
*
* @return The dataset.
*/
public IntervalCategoryDataset createDataset() {
TaskSeriesCollection collection = new TaskSeriesCollection();
TaskSeries series = null;
String[] lcCustNameArr = null;
String[] lcGaolDescArr = null;
String[] lcStartYrArr = null;
String[] lcEndYrArr = null;
lcGoalIdArr = null;

String tempVar = null;
String tempVar1 = null;
String[] tempVarArr = null;

/**
* This temp variable is to differentiate the goal names.
* Since 'TaskSeries' will display the goals that are having the same name into the same category
*/
for(int c=0; c<550; c++){
if(tempVar == null)
tempVar = " ";
else
tempVar = tempVar+" ";

if(tempVar1 == null)
tempVar1 = tempVar;
else
tempVar1 = tempVar1+","+tempVar;
}
tempVarArr = tempVar1.split(",");

if(lcCustName != null && !lcCustName.equalsIgnoreCase("") && lcCustName.indexOf(",") > 0)
lcCustNameArr = lcCustName.split(",");
else{
lcCustNameArr = new String[1];
lcCustNameArr[0] = lcCustName;
}

if(lcGaolDesc != null && !lcGaolDesc.equalsIgnoreCase("") && lcGaolDesc.indexOf("~") > 0)
lcGaolDescArr = lcGaolDesc.split("~");
else{
lcGaolDescArr = new String[1];
lcGaolDescArr[0] = lcGaolDesc;
}

if(lcStartYr != null && !lcStartYr.equalsIgnoreCase("") && lcStartYr.indexOf(",") > 0)
lcStartYrArr = lcStartYr.split(",");
else{
lcStartYrArr = new String[1];
lcStartYrArr[0] = lcStartYr;
}

if(lcEndYr != null && !lcEndYr.equalsIgnoreCase("") && lcEndYr.indexOf(",") > 0)
lcEndYrArr = lcEndYr.split(",");
else{
lcEndYrArr = new String[1];
lcEndYrArr[0] = lcEndYr;
}

if(lcGoalId != null && !lcGoalId.equalsIgnoreCase("") && lcGoalId.indexOf(",") > 0)
lcGoalIdArr = lcGoalId.split(",");
else{
lcGoalIdArr = new String[1];
lcGoalIdArr[0] = lcGoalId;
}

if(lcGoalType != null && !lcGoalType.equalsIgnoreCase("") && lcGoalType.indexOf(",") > 0)
lcGoalTypeArr = lcGoalType.split(",");
else{
lcGoalTypeArr = new String[1];
lcGoalTypeArr[0] = lcGoalType;
}



int goalTypeCounts[] = {0,0,0,0,0,0,0};
HashMap taskSeriesMap = new HashMap();
if(lcGaolDescArr != null){
for(int i=0; i<lcGaolDescArr.length; i++){
HashMap custGoalTypeMap = null;
HashMap custGoalIdMap = null;
HashMap custGoalTypesMap = null;
if (custGoals.containsKey(lcCustNameArr)) {
custGoalTypeMap = (HashMap)custGoals.get(lcCustNameArr);
custGoalIdMap = (HashMap)custGoalIds.get(lcCustNameArr);
custGoalTypesMap = (HashMap)custGoalTypes.get(lcCustNameArr);
} else {
custGoalTypeMap = new HashMap();
custGoalIdMap = new HashMap();
custGoalTypesMap = new HashMap();
custGoals.put(lcCustNameArr, custGoalTypeMap);
custGoalIds.put(lcCustNameArr, custGoalIdMap);
custGoalTypes.put(lcCustNameArr, custGoalTypesMap);
//Reset counts
goalTypeCounts = new int[] {0,0,0,0,0,0,0};
}
String seriesName = lcGoalTypeArr;
int goalType = Integer.parseInt(seriesName);
if (!custGoalTypeMap.containsKey(seriesName)) {
goalTypeCounts[goalType]++;
seriesName += "-" + goalTypeCounts[goalType];
custGoalTypeMap.put(seriesName, lcGaolDescArr);
custGoalIdMap.put(seriesName, lcGoalIdArr);
custGoalTypesMap.put(seriesName, lcGoalTypeArr[i]);
}
if (taskSeriesMap.containsKey(seriesName)) {
series = (TaskSeries)taskSeriesMap.get(seriesName);
} else {
series = new TaskSeries(seriesName);
taskSeriesMap.put(seriesName, series);
collection.add(series);
}
series.add(new Task(lcCustNameArr[i],dateYr(Integer.parseInt(lcStartYrArr[i])),dateYr(Integer.parseInt(lcEndYrArr[i])+1)));
}
int numCust = custGoals.keySet().size();
series = new TaskSeries("");
collection.add(series);

String custName = " ";
//Padding for upto 5 customers - the min number displayed
for (int j = numCust;j<LC_MIN_PERSONS;j++) {
series.add(new Task(custName,dateYr(0),dateYr(0)));

custName += " ";
}
}

customerList = collection.getColumnKeys();
return collection;
}

/**
* Utility method for creating <code>Date</code> objects.
*
* @param year the year.
*
* @return a date.
*/

private Date dateYr(int year) {

Calendar calendar = Calendar.getInstance();
calendar.set(year, 0, 1);
Date result = calendar.getTime();
return result;

}

/**
* Method to create custom lables
* @param dataset
* @param series
* @param category
* @return String
*/
public String generateLabel(CategoryDataset dataset, int series, int category){
String label="";
if (custGoals.containsKey(dataset.getColumnKey(category))) {
HashMap seriesMap = (HashMap)custGoals.get(dataset.getColumnKey(category));
if (seriesMap.containsKey(dataset.getRowKey(series))) {
//System.out.println("Goal lable ="+goalListCount+" = >"+(String)seriesMap.get(dataset.getRowKey(series)));
//label=(String)seriesMap.get(dataset.getRowKey(series));
//return " "+label;
return (String)seriesMap.get(dataset.getRowKey(series));
}

}
return "xxx";
}

/**
* Method to give protection year shading
* Arguments : End year
*/

public void chartProtectionYearShading(String protectionYear){
plot.clearRangeMarkers();
double start = dateYr(calendar.get(Calendar.YEAR)).getTime();
double end = dateYr(Integer.parseInt(protectionYear)).getTime();
IntervalMarker target = new IntervalMarker(start,end);
target.setLabel(Localeutil.getLocaleValue("LC_Applet_Currentprotection",locale));
target.setLabelFont(new Font("Monospace", Font.BOLD, 8));
target.setLabelAnchor(RectangleAnchor.LEFT);
target.setLabelTextAnchor(TextAnchor.CENTER_LEFT);
target.setLabelPaint(new Color(0x3A3939));
target.setPaint(new Color(232, 255, 232, 128));

plot.addRangeMarker(target, Layer.BACKGROUND);
}

/**
* Creates a chart.
*
* @param dataset the dataset.
*
* @return The chart.
*/

private JFreeChart createChart(IntervalCategoryDataset dataset) {
JFreeChart chart = ChartFactory.createGanttChart(
"", // chart title
"", // domain axis label
"", // range axis label
dataset, // data
false, // include legend
true, // tooltips
false // urls
);
plot = (CategoryPlot) chart.getPlot();
plot.setBackgroundPaint(new Color(0xFFFFFF)); // Setting chart plot BG Color
plot.setDomainGridlinesVisible(true); // Code to disable Horizontal Grid lines
plot.setDomainGridlinePosition(CategoryAnchor.END);
plot.setRangeGridlinesVisible(false); // Code to disable vertical grid lines

plot.getDomainAxis().setCategoryMargin(0);
plot.getDomainAxis().setLowerMargin(0.02);
plot.getDomainAxis().setUpperMargin(0.02);

//Display customer name
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setTickLabelFont(new Font("Monospace", Font.BOLD, 12));
domainAxis.setTickLabelPaint(Color.blue);
domainAxis.setAxisLineVisible(false);

/**
* To make customer to be wrapped
*/
domainAxis.setCategoryLabelPositionOffset(1);
domainAxis.setMaximumCategoryLabelLines(6);
domainAxis.setMaximumCategoryLabelWidthRatio(0.05f);
/**
* Code to display year axis
*/
ValueAxis valueAxis = (ValueAxis)plot.getRangeAxis();
valueAxis.setAutoRange(true);
double startLimit = dateYr(calendar.get(Calendar.YEAR)).getTime();
double endLimit = dateYr(Integer.parseInt(graphXLimit)).getTime();
valueAxis.setRange(startLimit,endLimit);
valueAxis.setAxisLineVisible(false);
valueAxis.setTickMarksVisible(true);
valueAxis.setTickLabelFont(new Font("Monospace", Font.PLAIN, 6));
valueAxis.setVerticalTickLabels(true);
valueAxis.setAxisLineVisible(false);
plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
((DateAxis)valueAxis).setTickUnit(new DateTickUnit(DateTickUnit.YEAR,2,dateFormat));

/**
* Code to display customer age axis
*/

int startAge = calendar.get(Calendar.YEAR)-Integer.parseInt(custDOB);
int endAge = Integer.parseInt(graphXLimit)-Integer.parseInt(custDOB);

NumberAxis axis2 = new NumberAxis(Localeutil.getLocaleValue("LC_Applet_YourAge",locale));
axis2.setRange(startAge, endAge);
axis2.setTickLabelFont(new Font("Monospace", Font.PLAIN, 6));
axis2.setLabelFont(new Font("Monospace", Font.BOLD, 8));
axis2.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
axis2.setAxisLineVisible(false);
plot.setRangeAxis(1, axis2);
plot.setRangeAxisLocation(1, AxisLocation.TOP_OR_RIGHT);
axis2.setTickUnit(new NumberTickUnit(2));

/**
* Sizing the graph for combined graph
*/
AxisSpace aspace = new AxisSpace();
aspace.setLeft(64);
aspace.setTop(15);
aspace.setBottom(12);


plot.setFixedDomainAxisSpace(aspace);
plot.setFixedRangeAxisSpace(aspace);

/**
* Code for Goal name display inside graph
*/
GanttRenderer renderer = (GanttRenderer) plot.getRenderer();
renderer.setDrawBarOutline(false);
renderer.setBaseItemLabelsVisible(true);
//renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator("{0}",NumberFormat.getInstance()));
renderer.setBaseItemLabelGenerator(this);

/**
* Code to customize bar's thickness
*/
renderer.setBaseItemLabelFont(new Font("Monospace", Font.PLAIN, 10));
renderer.setItemMargin(0.50);


renderer.setMaximumBarWidth(0.015);
renderer.setItemLabelAnchorOffset(0);
ItemLabelPosition position2 = new ItemLabelPosition(
ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT);
renderer.setPositiveItemLabelPosition(position2);





/** Category marker code
*/

// if(customerList.size() > 0){
// for(int i=0; i<customerList.size(); i++){
// CategoryMarker marker = new CategoryMarker(String.valueOf(customerList.get(i)),
// new Color(0xF4F4F4), new BasicStroke(1.0f));
// marker.setDrawAsLine(false);
// plot.addDomainMarker(marker, Layer.BACKGROUND);
// }
// }

/**
* Code for giving colors to the bars
*/
renderer.setSeriesPaint(0,Color.GRAY);
renderer.setSeriesPaint(1,Color.GREEN);
renderer.setSeriesPaint(2,Color.CYAN);
renderer.setSeriesPaint(3,Color.MAGENTA);


chart.setBackgroundPaint(new Color(0xFFFFFF)); // Setting chart Chart BG Color

return chart;
}

/**
* Creates a panel for the Graph
*
* @return A panel.
*/
public JPanel createDemoPanel() {
JFreeChart chart = createChart(createDataset());
ChartPanel cp = new ChartPanel(chart);
cp.setDomainZoomable(false);
cp.setRangeZoomable(false);
if(mouseFunctions != null && !mouseFunctions.equalsIgnoreCase("") && mouseFunctions.equalsIgnoreCase("yes"))
cp.addChartMouseListener(this);
cp.setPopupMenu(null);
// cp.setMinimumDrawWidth(0);
// cp.setMinimumDrawHeight(0);
//cp.setMaximumDrawWidth(4000);
//cp.setMaximumDrawHeight(10000);
//cp.setPreferredSize(new Dimension(270, 1000));
return cp;

}



/**
* Mouse action listener methods
*/
public void chartMouseClicked(ChartMouseEvent event) {

int mouseX = event.getTrigger().getX();
int mouseY = event.getTrigger().getY();
entity = (CategoryItemEntity) event.getEntity();

if (entity != null) {
System.out.println("Mouse clicked: " + entity.toString());

int idx = entity.getSeries();
CategoryDataset cds = entity.getDataset();
int catIdx = entity.getCategoryIndex();
//mouseClickedGoalName = cds.getRowKey(idx).toString();
/**
* Code to disable Remove menu for retirement goal
*/


if (custGoalIds.containsKey(cds.getColumnKey(catIdx))) {
HashMap idMap = (HashMap)custGoalIds.get(cds.getColumnKey(catIdx));
HashMap typeMap = (HashMap)custGoalTypes.get(cds.getColumnKey(catIdx));
HashMap descMap = (HashMap)custGoals.get(cds.getColumnKey(catIdx));
if (idMap.containsKey(cds.getRowKey(idx))) {
goalId = (String)idMap.get(cds.getRowKey(idx));
selectedGoalType = (String)typeMap.get(cds.getRowKey(idx));
mouseClickedGoalName = (String)descMap.get(cds.getRowKey(idx));
}
}
System.out.println("Goal Id clicked= ================================>" + goalId);
System.out.println("Goal Type clicked= ================================>" + selectedGoalType);
System.out.println("Goal Description clicked= ================================>" + mouseClickedGoalName);

if(selectedGoalType.equalsIgnoreCase("1")){
popupMenu = new JPopupMenu();
JMenuItem mi = new JMenuItem(Localeutil.getLocaleValue("LC_Applet_menu_analyse",locale));
mi.addActionListener(this);
popupMenu.add(mi);
popupMenu.show(chart, mouseX, mouseY);
}else{
popupMenu = new JPopupMenu();
JMenuItem mi = new JMenuItem(Localeutil.getLocaleValue("LC_Applet_menu_analyse",locale));
mi.addActionListener(this);
popupMenu.add(mi);
mi = new JMenuItem(Localeutil.getLocaleValue("LC_Applet_menu_remove",locale));
mi.addActionListener(this);
popupMenu.add(mi);
popupMenu.show(chart, mouseX, mouseY);
}

}
}

public void chartMouseMoved(ChartMouseEvent arg0) {
// TODO Auto-generated method stub

}

public void actionPerformed(ActionEvent event) {
String menuText = event.getActionCommand();
Object values[];
values = new Object[3];
/**
* Code to get the goal id for mouse clicked bar
*/
// if(goalList.size() > 0){
// for(int i=0; i<goalList.size(); i++){
// if(mouseClickedGoalName.equals(goalList.get(i).toString())){
// values[0] = lcGoalIdArr[i];
// values[1] = lcGoalTypeArr[i];
// values[2] = mouseClickedGoalName;
// }
// }
// }
values[0] = goalId;
values[1] = selectedGoalType;
values[2] = mouseClickedGoalName;

if(menuText.equalsIgnoreCase(Localeutil.getLocaleValue("LC_Applet_menu_analyse",locale))){
// System.out.println("Analyse Called !!!!");
jsObject.call("solutionCallArguments", values);
}
else if(menuText.equalsIgnoreCase(Localeutil.getLocaleValue("LC_Applet_menu_remove",locale))){
// System.out.println("Remove Called !!!!");
jsObject.call("appletCallArguments", values);

}

}

public String generateColumnLabel(CategoryDataset arg0, int arg1) {
// TODO Auto-generated method stub
return "column " + arg1;
}

public String generateRowLabel(CategoryDataset arg0, int arg1) {
// TODO Auto-generated method stub
return "row " + arg1;
}

}

Locked