[Schmitzm-commits] r1108 - in trunk: src/schmitzm/jfree src/schmitzm/jfree/chart/style src_junit/schmitzm/jfree src_junit/schmitzm/jfree/feature/style src_junit/schmitzm/swing
scm-commit@wald.intevation.org
scm-commit at wald.intevation.org
Thu Oct 14 18:42:43 CEST 2010
Author: mojays
Date: 2010-10-14 18:42:41 +0200 (Thu, 14 Oct 2010)
New Revision: 1108
Modified:
trunk/src/schmitzm/jfree/JFreeChartUtil.java
trunk/src/schmitzm/jfree/chart/style/AbstractChartStyle.java
trunk/src_junit/schmitzm/jfree/JFreeChartUtilTest.java
trunk/src_junit/schmitzm/jfree/feature/style/FeatureChartStyleTest.java
trunk/src_junit/schmitzm/swing/TestingUtil.java
Log:
Chart-Updates:
- new utility methods JFreeChartUtil.isDatasetEmpty(.), .resetRangeAxisTickLabelVisibiliy(.)
- on legend split the legend border is only shown when legend items are present
- AbstractChartStyle: when multiple range axes are used with unequal ranges (positive/negative range), the axis ranges are automatically adjusted to have a common 0-line
Modified: trunk/src/schmitzm/jfree/JFreeChartUtil.java
===================================================================
--- trunk/src/schmitzm/jfree/JFreeChartUtil.java 2010-10-14 10:39:07 UTC (rev 1107)
+++ trunk/src/schmitzm/jfree/JFreeChartUtil.java 2010-10-14 16:42:41 UTC (rev 1108)
@@ -33,6 +33,9 @@
import java.awt.Color;
import java.awt.Stroke;
import java.text.DecimalFormat;
+import java.text.FieldPosition;
+import java.text.NumberFormat;
+import java.text.ParsePosition;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
@@ -153,6 +156,7 @@
* */
public static final String DUMMY_SERIES_PREFIX = "DUMMY_";
+
/**
* Sets all chart legends (in)visible.
*
@@ -202,19 +206,27 @@
);
LegendTitle legend1 = new LegendTitle(lis1);
legend1.setMargin(new RectangleInsets(2, 2, 2, 2));
- legend1.setFrame(new BlockBorder());
-
+ // Create border, only if legend items are present (avoid
+ // border around empty legend, because it is shown as
+ // vertical line)
+ if ( lis1.getLegendItems().getItemCount() > 0 )
+ legend1.setFrame(new BlockBorder());
+
// create right legend for second dataset legend items
LegendItemSource lis2 = new FilteredLegendItemSource(
(LegendItemSource)JFreeChartUtil.getRendererForDataset(chart.getPlot(), 1)
);
LegendTitle legend2 = new LegendTitle(lis2);
legend2.setMargin(new RectangleInsets(2, 2, 2, 2));
- legend2.setFrame(new BlockBorder());
-
+ // Create border, only if legend items are present (avoid
+ // border around empty legend, because it is shown as
+ // vertical line)
+ if ( lis2.getLegendItems().getItemCount() > 0 )
+ legend2.setFrame(new BlockBorder());
+
// combine the legends in a block
BlockContainer container = new BlockContainer(new BorderArrangement());
- container.add(legend1, RectangleEdge.LEFT);
+ container.add(legend1, RectangleEdge.LEFT);
container.add(legend2, RectangleEdge.RIGHT);
container.add(new EmptyBlock(2000, 0));
@@ -223,7 +235,54 @@
legends.setPosition(RectangleEdge.BOTTOM);
chart.addSubtitle(legends);
}
+
+ /**
+ * When all datasets for a range axis are empty, JFreeChart
+ * shows a default range with tick labels between 0.0 and 1.0.
+ * That looks not nice for us (especially Stefan!). We (Stefan) want
+ * no tick labels in this case.<br>
+ * This method first disables all tick labels for all axis. Then
+ * it checks all datasets and (if not empty) (re)enable the tick labels
+ * for the corresponding range axis
+ * @param plot the plot the tick labels should be reset for
+ */
+ public static void resetRangeAxisTickLabelVisibiliy(JFreeChart chart) {
+ if ( chart != null )
+ resetRangeAxisTickLabelVisibiliy(chart.getPlot());
+ }
+
+ /**
+ * When all datasets for a range axis are empty, JFreeChart
+ * shows a default range with tick labels between 0.0 and 1.0.
+ * That looks not nice for us (especially Stefan!). We (Stefan) want
+ * no tick labels in this case.<br>
+ * This method first disables all tick labels for all axis. Then
+ * it checks all datasets and (if not empty) (re)enable the tick labels
+ * for the corresponding range axis
+ * @param plot the plot the tick labels should be reset for
+ */
+ public static void resetRangeAxisTickLabelVisibiliy(Plot plot) {
+ if ( plot == null )
+ return;
+ int datasetCount = JFreeChartUtil.getDatasetCountFromPlot(plot);
+ // first disable the tick labels for all range axis
+ for (int i=0; i<datasetCount; i++) {
+ Dataset dataset = JFreeChartUtil.getDatasetFromPlot(plot, i);
+ ValueAxis axis = JFreeChartUtil.getRangeAxisForDataset(plot, dataset);
+ if ( axis != null )
+ axis.setTickLabelsVisible(false);
+ }
+ // (re)enable the tick labels for the axis whose dataset(s) are
+ // not empty
+ for (int i=0; i<datasetCount; i++) {
+ Dataset dataset = JFreeChartUtil.getDatasetFromPlot(plot, i);
+ ValueAxis axis = JFreeChartUtil.getRangeAxisForDataset(plot, dataset);
+ if ( axis != null && !JFreeChartUtil.isDatasetEmpty(dataset, true) )
+ axis.setTickLabelsVisible(true);
+ }
+ }
+
/**
* Fires a change event to all {@link PlotChangeListener} connected to the
* plot.
@@ -585,7 +644,47 @@
dataset = getDatasetFromPlot((Plot)object);
return dataset;
}
+
+
+ /**
+ * Checks whether a dataset is empty.
+ * @param dataset a dataset
+ */
+ public static boolean isDatasetEmpty(Dataset dataset, boolean checkEveryItemForNull) {
+ if ( dataset instanceof XYDataset ) {
+ XYDataset xyDataset = (XYDataset)dataset;
+ for (int seriesIdx=0; seriesIdx<xyDataset.getSeriesCount(); seriesIdx++)
+ if ( !checkEveryItemForNull ) {
+ if ( xyDataset.getItemCount(seriesIdx) > 0 )
+ return false;
+ } else {
+ for (int itemIdx=0; itemIdx<xyDataset.getItemCount(seriesIdx); itemIdx++)
+ if ( xyDataset.getY(seriesIdx, itemIdx) != null )
+ return false;
+ }
+ return true;
+ } else if ( dataset instanceof CategoryDataset ) {
+ CategoryDataset catDataset = (CategoryDataset)dataset;
+ if ( !checkEveryItemForNull )
+ return catDataset.getRowCount() > 0;
+ for (int col=0; col<catDataset.getColumnCount(); col++)
+ for (int row=0; row<catDataset.getRowCount(); row++)
+ if ( catDataset.getValue(row, col) != null )
+ return false;
+ } else if ( dataset instanceof PieDataset ) {
+ PieDataset pieDataset = (PieDataset)dataset;
+ if ( !checkEveryItemForNull )
+ return pieDataset.getItemCount() > 0;
+ for ( int j=0; j<pieDataset.getItemCount(); j++ )
+ if ( pieDataset.getValue(j) != null )
+ return false;
+ return true;
+ } else
+ LOGGER.warn("Could not determine emptyness for dataset: "+LangUtil.getSimpleClassName(dataset));
+ return true;
+ }
+
/**
* Returns the series index for a series key in a dataset.
* For {@link PieDataset} this method always returns 0 (unless
Modified: trunk/src/schmitzm/jfree/chart/style/AbstractChartStyle.java
===================================================================
--- trunk/src/schmitzm/jfree/chart/style/AbstractChartStyle.java 2010-10-14 10:39:07 UTC (rev 1107)
+++ trunk/src/schmitzm/jfree/chart/style/AbstractChartStyle.java 2010-10-14 16:42:41 UTC (rev 1108)
@@ -48,6 +48,7 @@
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.Axis;
import org.jfree.chart.axis.NumberAxis;
+import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.CategoryToolTipGenerator;
import org.jfree.chart.labels.PieSectionLabelGenerator;
import org.jfree.chart.labels.StandardCategoryToolTipGenerator;
@@ -68,6 +69,8 @@
import org.jfree.chart.urls.StandardPieURLGenerator;
import org.jfree.chart.urls.StandardXYURLGenerator;
import org.jfree.chart.urls.XYURLGenerator;
+import org.jfree.data.Range;
+import org.jfree.data.general.Dataset;
import schmitzm.jfree.JFreeChartUtil;
import schmitzm.jfree.chart.StyledToolTipGenerator;
@@ -75,8 +78,8 @@
import skrueger.geotools.CopyableUtil;
/**
- * This class provides an abstract implementation for chart styles.
- * It implements the variables and methods for maintaining the type, the title(s)
+ * This class provides an abstract implementation for chart styles. It
+ * implements the variables and methods for maintaining the type, the title(s)
* and flags of the {@link ChartStyle} interface.
* @author <a href="mailto:Martin.Schmitz at koeln.de">Martin Schmitz</a>
* @version 1.0
@@ -94,13 +97,15 @@
protected CategoryURLGenerator URLGEN_CAT = new StandardCategoryURLGenerator();
/** URL generator used for Pie-Charts. */
protected PieURLGenerator URLGEN_PIE = new StandardPieURLGenerator();
-
+
/** Logger for this class */
protected final Category LOGGER = LangUtil.createLogger(this);
/** Holds a (unique) ID for the style. */
protected String id = "";
- /** Holds the chart type.
- * @see ChartStyle#ChartType */
+ /**
+ * Holds the chart type.
+ * @see ChartStyle#ChartType
+ */
protected ChartType type = null;
/** Holds the chart title. */
protected ChartLabelStyle titleStyle = new ChartLabelStyle();
@@ -111,7 +116,7 @@
/** Stores whether a border is shown around the whole chart. */
protected boolean borderVisible = false;
/** Holds the styles of the chart axis. */
- protected Map<Integer,ChartAxisStyle> axisStyle = new HashMap<Integer,ChartAxisStyle>();
+ protected Map<Integer, ChartAxisStyle> axisStyle = new HashMap<Integer, ChartAxisStyle>();
/** Holds the plot orientation (horizontal/vertical). */
protected PlotOrientation orientation = null;
/** Stores whether a legend is generated for the chart (Default: true). */
@@ -121,7 +126,7 @@
/** Stores whether URLs are generated for the chart (Default: true). */
protected boolean urls = true;
/** Holds the styles for the chart renderers. */
- protected Map<Integer,ChartRendererStyle> rendererStyle = new HashMap<Integer,ChartRendererStyle>();
+ protected Map<Integer, ChartRendererStyle> rendererStyle = new HashMap<Integer, ChartRendererStyle>();
/** Holds the maximum dataset index for which a renderer is specified. */
protected int maxRendererDatasetIdx = -1;
/** Holds the style for the chart's plot. */
@@ -134,87 +139,93 @@
* @param id a (unique) ID for the style
*/
public AbstractChartStyle(String id) {
- this( id, ChartType.LINE );
+ this(id, ChartType.LINE);
}
/**
* Creates a style with default values.
- * @param id a (unique) ID for the style
+ * @param id a (unique) ID for the style
* @param type style type
*/
public AbstractChartStyle(String id, ChartType type) {
- this(id,type,null,null,null,true,true,true);
+ this(id, type, null, null, null, true, true, true);
}
/**
* Creates a style.
- * @param id a (unique) ID for the style
- * @param type style type
- * @param title title for the chart
- * @param xTitle title for the chart's X-axis
- * @param yTitle title for the chart's Y-axis
- * @param legend flag whether a legend is generated
+ * @param id a (unique) ID for the style
+ * @param type style type
+ * @param title title for the chart
+ * @param xTitle title for the chart's X-axis
+ * @param yTitle title for the chart's Y-axis
+ * @param legend flag whether a legend is generated
* @param tooltips flag whether toolstips are generated
- * @param urls flag whether URLs are generated
+ * @param urls flag whether URLs are generated
*/
- public AbstractChartStyle(String id, ChartType type,
- String title, String xTitle, String yTitle,
- boolean legend, boolean tooltips, boolean urls) {
+ public AbstractChartStyle(String id, ChartType type, String title,
+ String xTitle, String yTitle, boolean legend, boolean tooltips,
+ boolean urls) {
this.id = id;
setType(type);
setLegend(legend);
setTooltips(tooltips);
setURLs(urls);
getTitleStyle().setLabel(title);
- if ( xTitle != null )
- setAxisStyle(DOMAIN_AXIS, new ChartAxisStyle(xTitle,Color.BLACK,0.0,0.0) );
- if ( yTitle != null )
- setAxisStyle(RANGE_AXIS, new ChartAxisStyle(yTitle,Color.BLACK,0.0,0.0) );
-
-// System.out.println("HASH = "+hashCode());
+ if (xTitle != null)
+ setAxisStyle(DOMAIN_AXIS, new ChartAxisStyle(xTitle, Color.BLACK, 0.0,
+ 0.0));
+ if (yTitle != null)
+ setAxisStyle(RANGE_AXIS,
+ new ChartAxisStyle(yTitle, Color.BLACK, 0.0, 0.0));
+
+ // System.out.println("HASH = "+hashCode());
}
-
+
/**
* Creates a (deep) clone of this chart style.
*/
@Override
public abstract AbstractChartStyle copy();
-
+
/**
- * Copies all properties of this chart style to another
- * chart style.
- * @param dest destination object (if {@code null} the copy
- * is created by {@link #copy()})
+ * Copies all properties of this chart style to another chart style.
+ * @param dest destination object (if {@code null} the copy is created by
+ * {@link #copy()})
* @return {@code dest} or the new instance
* @exception IllegalArgumentException if {@code dest} is no
- * {@link AbstractChartStyle}
+ * {@link AbstractChartStyle}
*/
@Override
public ChartStyle copyTo(ChartStyle dest) {
- if ( dest == null )
+ if (dest == null)
return copy();
- if ( !(dest instanceof AbstractChartStyle) )
- throw new IllegalArgumentException(LangUtil.getSimpleClassName(this)+".copy(..) can not be applied on "+LangUtil.getSimpleClassName(dest));
+ if (!(dest instanceof AbstractChartStyle))
+ throw new IllegalArgumentException(LangUtil.getSimpleClassName(this) +
+ ".copy(..) can not be applied on " +
+ LangUtil.getSimpleClassName(dest));
- AbstractChartStyle destStyle = (AbstractChartStyle)dest;
+ AbstractChartStyle destStyle = (AbstractChartStyle) dest;
destStyle.id = getID();
- destStyle.setType( getType() );
- destStyle.setTitleStyle( CopyableUtil.copyOrCreate(getTitleStyle(), destStyle.getTitleStyle()) );
- destStyle.setDescStyle( CopyableUtil.copyOrCreate(getDescStyle(), destStyle.getDescStyle()) );
- destStyle.setBackground( getBackground() );
- destStyle.setBorderVisible( isBorderVisible() );
- destStyle.setOrientation( getOrientation() );
- destStyle.setLegend( hasLegend() );
- destStyle.setTooltips( hasTooltips() );
- destStyle.setURLs( hasURLs() );
- destStyle.setPlotStyle( CopyableUtil.copyOrCreate(getPlotStyle(), destStyle.getPlotStyle()) );
-
+ destStyle.setType(getType());
+ destStyle.setTitleStyle(CopyableUtil.copyOrCreate(getTitleStyle(),
+ destStyle.getTitleStyle()));
+ destStyle.setDescStyle(CopyableUtil.copyOrCreate(getDescStyle(),
+ destStyle.getDescStyle()));
+ destStyle.setBackground(getBackground());
+ destStyle.setBorderVisible(isBorderVisible());
+ destStyle.setOrientation(getOrientation());
+ destStyle.setLegend(hasLegend());
+ destStyle.setTooltips(hasTooltips());
+ destStyle.setURLs(hasURLs());
+ destStyle.setPlotStyle(CopyableUtil.copyOrCreate(getPlotStyle(),
+ destStyle.getPlotStyle()));
+
destStyle.axisStyle.clear();
- for ( Integer axis : axisStyle.keySet() )
- destStyle.setAxisStyle(axis, getAxisStyle(axis).copy() );
+ for (Integer axis : axisStyle.keySet())
+ destStyle.setAxisStyle(axis, getAxisStyle(axis).copy());
destStyle.rendererStyle.clear();
- for ( Integer renderer : rendererStyle.keySet() )
- destStyle.setRendererStyle(renderer, getRendererStyle(renderer).copy() );
+ for (Integer renderer : rendererStyle.keySet())
+ destStyle.setRendererStyle(renderer, getRendererStyle(renderer).copy());
return destStyle;
}
@@ -263,15 +274,14 @@
public ChartLabelStyle getTitleStyle() {
return titleStyle;
}
-
+
/**
* Sets the style of the charts title.
- * @param style the new style (if {@code null} the style is
- * reset to an empty default style, so that the
- * getter method always can be accessed!)
+ * @param style the new style (if {@code null} the style is reset to an empty
+ * default style, so that the getter method always can be accessed!)
*/
public void setTitleStyle(ChartLabelStyle style) {
- if ( style == null )
+ if (style == null)
style = new ChartLabelStyle();
titleStyle = style;
}
@@ -297,7 +307,7 @@
public Color getBackground() {
return bgPaint;
}
-
+
/**
* Sets the background color of the chart.
* @param paint the background color for the chart
@@ -312,7 +322,7 @@
public boolean isBorderVisible() {
return this.borderVisible;
}
-
+
/**
* Sets whether a border is shown around the whole chart.
*/
@@ -366,8 +376,8 @@
* Returns the axis count.
*/
public int getAxisCount() {
-//MS: map size is not automatically the axis count
-// return axisStyle.size();
+ // MS: map size is not automatically the axis count
+ // return axisStyle.size();
return maxAxisIdx + 1;
}
@@ -379,7 +389,7 @@
public ChartAxisStyle getAxisStyle(int axis) {
return axisStyle.get(axis);
}
-
+
/**
* Sets the style of a chart axis.
* @param axis axis number (0=domain, 1=range, ...)
@@ -387,24 +397,22 @@
*/
public void setAxisStyle(int axis, ChartAxisStyle style) {
axisStyle.put(axis, style);
- maxAxisIdx = LangUtil.max( axisStyle.keySet() );
+ maxAxisIdx = LangUtil.max(axisStyle.keySet());
}
-
+
/**
* Updates the unitVisible parameter for all axes at once.
- *
- * @param visible
- * <code>true</code> if unit string shall be displayed in the
- * chart.
+ * @param visible <code>true</code> if unit string shall be displayed in the
+ * chart.
*/
@Override
public void setUnitVisible(boolean visible) {
- // TODO MArtin! Funktioniert so leider nicht. Warum ist hier
- // getAxisCount() immer 0 ????
- for (int axisIndex = 0; axisIndex < getAxisCount(); axisIndex++) {
- if ( getAxisStyle(axisIndex) != null )
- getAxisStyle(axisIndex).setUnitVisible(visible);
- }
+ // TODO MArtin! Funktioniert so leider nicht. Warum ist hier
+ // getAxisCount() immer 0 ????
+ for (int axisIndex = 0; axisIndex < getAxisCount(); axisIndex++) {
+ if (getAxisStyle(axisIndex) != null)
+ getAxisStyle(axisIndex).setUnitVisible(visible);
+ }
}
/**
@@ -422,7 +430,7 @@
public ChartRendererStyle getRendererStyle(int dataset) {
return rendererStyle.get(dataset);
}
-
+
/**
* Sets the style of a dataset renderer.
* @param dataset dataset number (starting with 0)
@@ -430,7 +438,7 @@
*/
public void setRendererStyle(int dataset, ChartRendererStyle style) {
rendererStyle.put(dataset, style);
- maxRendererDatasetIdx = LangUtil.max( -1, rendererStyle.keySet() );
+ maxRendererDatasetIdx = LangUtil.max(-1, rendererStyle.keySet());
}
/**
@@ -440,7 +448,7 @@
public ChartPlotStyle getPlotStyle() {
return plotStyle;
}
-
+
/**
* Sets the style of the chart's plot.
* @param style style for the plot
@@ -542,6 +550,8 @@
// All datasets (except the primary) are mapped to this
// secondary axis
if ( getAxisCount() > 2 ) {
+ ValueAxis rangeAxis0 = null;
+ ValueAxis rangeAxis1 = null;
if ( chart.getPlot() instanceof XYPlot ) {
XYPlot plot = chart.getXYPlot();
// add the yet missing axis
@@ -551,6 +561,9 @@
int datasetCount = reducedCountForSpecialStyle(this,plot,plot.getDatasetCount());
for (int i=1; i<datasetCount; i++)
plot.mapDatasetToRangeAxis(i, 1);
+ // remember axis for adjustments below
+ rangeAxis0 = plot.getRangeAxis(0);
+ rangeAxis1 = plot.getRangeAxis(1);
} else if ( chart.getPlot() instanceof CategoryPlot ) {
CategoryPlot plot = chart.getCategoryPlot();
// add the yet missing axis
@@ -560,11 +573,29 @@
int datasetCount = reducedCountForSpecialStyle(this,plot,plot.getDatasetCount());
for (int i=1; i<datasetCount; i++)
plot.mapDatasetToRangeAxis(i, 1);
+ // remember axis for adjustments below
+ rangeAxis0 = plot.getRangeAxis(0);
+ rangeAxis1 = plot.getRangeAxis(1);
} else
LOGGER.warn("Plot does not support a secondary range axis: "+LangUtil.getSimpleClassName(chart.getPlot()));
+
+ // if one axis shows a negative range and the other axis shows
+ // a positive range, JFreeChart does NOT homogenize the 0-line, so
+ // that the 0-line for the one axis is on top of the chart and the
+ // other 0-line on the bottom site.
+ // This looks not nice! We want a common 0-line for both axis.
+ // --> Adjust the axis ranges
+ if (rangeAxis0 != null && rangeAxis1 != null) {
+ if ( Math.signum(rangeAxis0.getLowerBound()) != Math.signum(rangeAxis1.getLowerBound()) ) {
+ double span0 = Math.max(Math.abs(rangeAxis0.getLowerBound()),Math.abs(rangeAxis0.getUpperBound()));
+ rangeAxis0.setRange(new Range(-span0, +span0));
+ double span1 = Math.max(Math.abs(rangeAxis1.getLowerBound()),Math.abs(rangeAxis1.getUpperBound()));
+ rangeAxis1.setRange(new Range(-span1, +span1));
+ }
+ }
+
}
-
// Style the chart axis
Vector<Axis> chartAxis = new Vector<Axis>();
if ( chart.getPlot() instanceof XYPlot ) {
@@ -583,9 +614,8 @@
}
for (int i=0; i<chartAxis.size(); i++) {
ChartAxisStyle axisStyle = getAxisStyle(i);
- if ( axisStyle != null ) {
+ if ( axisStyle != null )
axisStyle.applyToAxis( chartAxis.elementAt(i) );
- }
else
LOGGER.warn("Style contains no style definition for axis "+i);
}
@@ -597,20 +627,23 @@
JFreeChartUtil.setLegendVisible(chart, hasLegend());
}
-
+
/**
* Reduces a count (of Datasets or Renderer) in some special cases.
- * @param style the chart style
- * @param plot the plot
- * @param count the count (of Datasets or Renderer)
+ * @param style the chart style
+ * @param plot the plot
+ * @param count the count (of Datasets or Renderer)
*/
- private static int reducedCountForSpecialStyle(ChartStyle style, Plot plot, int count) {
+ private static int reducedCountForSpecialStyle(ChartStyle style, Plot plot,
+ int count) {
// In a ScatterChart with Regression line, there is a additional dataset and
- // renderer (the last one!) for which the "normal" chart and axis properties should not
+ // renderer (the last one!) for which the "normal" chart and axis properties
+ // should not
// be applied
- if ( style instanceof ScatterChartStyle && ((ScatterChartStyle)style).isRegressionLineVisible() )
- count--;
-
+ if (style instanceof ScatterChartStyle &&
+ ((ScatterChartStyle) style).isRegressionLineVisible())
+ count--;
+
return count;
}
}
Modified: trunk/src_junit/schmitzm/jfree/JFreeChartUtilTest.java
===================================================================
--- trunk/src_junit/schmitzm/jfree/JFreeChartUtilTest.java 2010-10-14 10:39:07 UTC (rev 1107)
+++ trunk/src_junit/schmitzm/jfree/JFreeChartUtilTest.java 2010-10-14 16:42:41 UTC (rev 1108)
@@ -14,5 +14,4 @@
public void testCreateDefaultStrokeFloatFloatArray2() {
JFreeChartUtil.createDefaultStroke(2f, (Float[])null);
}
-
}
Modified: trunk/src_junit/schmitzm/jfree/feature/style/FeatureChartStyleTest.java
===================================================================
--- trunk/src_junit/schmitzm/jfree/feature/style/FeatureChartStyleTest.java 2010-10-14 10:39:07 UTC (rev 1107)
+++ trunk/src_junit/schmitzm/jfree/feature/style/FeatureChartStyleTest.java 2010-10-14 16:42:41 UTC (rev 1108)
@@ -36,6 +36,7 @@
import org.opengis.feature.simple.SimpleFeatureType;
import schmitzm.io.IOUtil;
+import schmitzm.jfree.JFreeChartUtil;
import schmitzm.jfree.chart.style.BasicChartStyle;
import schmitzm.jfree.chart.style.ChartAxisStyle;
import schmitzm.jfree.chart.style.ChartLabelStyle;
@@ -98,6 +99,54 @@
TestingUtil.testGui(chart, "barchart");
}
+
+ @Test
+ public void testAutomaticAdjustmentsOnDualAxes() throws Throwable {
+ ChartAxisStyle domainAxisStyle = new ChartAxisStyle("jahreszahlen",
+ Color.red, 0., 0.);
+ ChartAxisStyle rangeAxisStyle = new ChartAxisStyle("deut. maenner",
+ Color.green, 0., 0.);
+ ChartAxisStyle rangeAxisStyle2 = new ChartAxisStyle(
+ "Weibl. Bevölkerung", Color.blue, 0., 0.);
+
+ BasicChartStyle barChartStyle = new BasicChartStyle(
+ "testBarChartWith2Axis", ChartType.BAR);
+
+ barChartStyle.setAxisStyle(0, domainAxisStyle);
+ barChartStyle.setAxisStyle(1, rangeAxisStyle);
+ barChartStyle.setAxisStyle(2, rangeAxisStyle2);
+
+ assertNull("Wenn nicht explizit gesetzt wird null geliefert",
+ barChartStyle.getRendererStyle(0));
+
+ ChartRendererStyle chartRendererStyle = new ChartRendererStyle();
+ chartRendererStyle.setDefaultPaint(Color.blue);
+ chartRendererStyle.setSeriesPaint(0, Color.green);
+ chartRendererStyle.setSeriesPaint(1, Color.red);
+ chartRendererStyle.setSeriesPaint(2, Color.GRAY);
+ barChartStyle.setRendererStyle(0, chartRendererStyle);
+ assertEquals(3, chartRendererStyle.getSeriesCount());
+
+ // Renderer style for the series dealing with the
+ // secondary axis.
+ ChartRendererStyle chartRendererStyle2 = new ChartRendererStyle();
+ chartRendererStyle2.setDefaultLineDashAttributes(5.0f, 5.0f);
+ chartRendererStyle2.setSeriesLineWidth(1, 10);
+ chartRendererStyle2.setSeriesLineDashAttributes(1, 10f, 10f);
+ barChartStyle.setRendererStyle(1, chartRendererStyle2);
+
+ CategoryDataset data1 = createSampleCategoryDataset1(true,1);
+ CategoryDataset data2 = createSampleCategoryDataset2(true,-1);
+
+ JFreeChart barChart = barChartStyle.applyToDataset(data1, data2);
+ JFreeChartUtil.resetRangeAxisTickLabelVisibiliy(barChart);
+
+ assertNotNull("applyToDataset lieferte null!", barChart);
+
+ TestingUtil.testGui(barChart, "bar chart",-1);
+ }
+
+
@Ignore
@Test
public void testLineChartDualAxis() throws Throwable {
@@ -180,10 +229,10 @@
* frames etc.
**/
- public CategoryDataset createSampleCategoryDataset1(boolean nullSecondary) {
+ public CategoryDataset createSampleCategoryDataset1(boolean nullSecondary, int valuesType) {
// row keys...
String series1 = "Series 1";
- String series2 = "Dummy 1";
+ String series2 = JFreeChartUtil.DUMMY_SERIES_PREFIX+"1";
// column keys...
String category1 = "Category 1";
@@ -194,12 +243,15 @@
// create the dataset...
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
- dataset.addValue(1.0, series1, category1);
- dataset.addValue(4.0, series1, category2);
- dataset.addValue(3.0, series1, category3);
- dataset.addValue(5.0, series1, category4);
-
- if (nullSecondary) {
+ // ValuesType 0 means an empty dataset
+ if ( valuesType != 0 ) {
+ dataset.addValue(1.0 * valuesType, series1, category1);
+ dataset.addValue(4.0 * valuesType, series1, category2);
+ dataset.addValue(3.0 * valuesType, series1, category3);
+ dataset.addValue(5.0 * valuesType, series1, category4);
+ }
+
+ if (nullSecondary && valuesType != 0) {
dataset.addValue(null, series2, category1);
dataset.addValue(null, series2, category2);
dataset.addValue(null, series2, category3);
@@ -208,9 +260,9 @@
return dataset;
}
- public CategoryDataset createSampleCategoryDataset2(boolean nullPrimary) {
+ public CategoryDataset createSampleCategoryDataset2(boolean nullPrimary, int valuesType) {
// row keys...
- String series1 = "Dummy 2";
+ String series1 = JFreeChartUtil.DUMMY_SERIES_PREFIX+"2";
String series2 = "Series 2";
// column keys...
@@ -222,23 +274,26 @@
// create the dataset...
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
- if (nullPrimary) {
+ // ValuesType 0 means an empty dataset
+ if (nullPrimary && valuesType != 0) {
dataset.addValue(null, series1, category1);
dataset.addValue(null, series1, category2);
dataset.addValue(null, series1, category3);
dataset.addValue(null, series1, category4);
}
- dataset.addValue(75.0, series2, category1);
- dataset.addValue(87.0, series2, category2);
- dataset.addValue(96.0, series2, category3);
- dataset.addValue(68.0, series2, category4);
+ // ValuesType 0 means an empty dataset
+ if ( valuesType != 0 ) {
+ dataset.addValue(75.0 * valuesType, series2, category1);
+ dataset.addValue(87.0 * valuesType, series2, category2);
+ dataset.addValue(96.0 * valuesType, series2, category3);
+ dataset.addValue(68.0 * valuesType, series2, category4);
+ }
+ return dataset;
- return dataset;
-
}
- @Test
+ @Test
@Ignore
public void testBarChartDualAxisWithSampleData() throws Throwable {
ChartAxisStyle domainAxisStyle = new ChartAxisStyle("jahreszahlen",
@@ -274,8 +329,8 @@
chartRendererStyle2.setSeriesLineDashAttributes(1, 10f, 10f);
barChartStyle.setRendererStyle(1, chartRendererStyle2);
- CategoryDataset data1 = createSampleCategoryDataset1(true);
- CategoryDataset data2 = createSampleCategoryDataset2(true);
+ CategoryDataset data1 = createSampleCategoryDataset1(true,1);
+ CategoryDataset data2 = createSampleCategoryDataset2(true,1);
JFreeChart barChart = barChartStyle.applyToDataset(data1, data2);
assertNotNull("applyToDataset lieferte null!", barChart);
Modified: trunk/src_junit/schmitzm/swing/TestingUtil.java
===================================================================
--- trunk/src_junit/schmitzm/swing/TestingUtil.java 2010-10-14 10:39:07 UTC (rev 1107)
+++ trunk/src_junit/schmitzm/swing/TestingUtil.java 2010-10-14 16:42:41 UTC (rev 1108)
@@ -51,283 +51,280 @@
// "java.lang.Exception: No runnable methods"
public class TestingUtil {
- /**
- * Number of seconds to wait until a GUI should be closed by default. Can be
- * set to -1 to always wait forever.
- */
- private static final int WAIT_MAX_DEFAULT = 3;
- /**
- * All these GUI-initiating testGui(...) methods are only executed if the
- * system is not running in headless mode.
- */
- public static final boolean INTERACTIVE = !GraphicsEnvironment.isHeadless();
+ /**
+ * Number of seconds to wait until a GUI should be closed by default. Can be
+ * set to -1 to always wait forever.
+ */
+ private static final int WAIT_MAX_DEFAULT = 3;
+ /**
+ * All these GUI-initiating testGui(...) methods are only executed if the
+ * system is not running in headless mode.
+ */
+ public static final boolean INTERACTIVE = !GraphicsEnvironment.isHeadless();
- /**
- * Opens a {@link JFrame} and shows the passed {@link JComponent}. If a
- * {@link ExceptionDialog} is opens in the GUI, an exception is thrown.<br/>
- * The test is skipped if the JVM is running headless.
- *
- * @param gui
- * @param title
- * can be used to explain the tests what to check
- * @param waitMax
- * Maximum seconds to wait until the GUI should automatically
- * close, set -1 for unlimieted
- */
- public static void testGui(Component gui, String title, int waitMax)
- throws Throwable {
+ /**
+ * Opens a {@link JFrame} and shows the passed {@link JComponent}. If a
+ * {@link ExceptionDialog} is opens in the GUI, an exception is thrown.<br/>
+ * The test is skipped if the JVM is running headless.
+ * @param gui
+ * @param title can be used to explain the tests what to check
+ * @param waitMax Maximum seconds to wait until the GUI should automatically
+ * close, set -1 for unlimieted
+ */
+ public static void testGui(Component gui, String title, int waitMax)
+ throws Throwable {
- if (GraphicsEnvironment.isHeadless())
- return;
+ if (GraphicsEnvironment.isHeadless())
+ return;
- final AtomicBoolean stopFlag = new AtomicBoolean(false);
+ final AtomicBoolean stopFlag = new AtomicBoolean(false);
- final AtomicReference<Throwable> err = new AtomicReference<Throwable>();
+ final AtomicReference<Throwable> err = new AtomicReference<Throwable>();
- ExceptionDialog.addListener(new ActionListener() {
+ ExceptionDialog.addListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- err.set((Throwable) e.getSource());
- stopFlag.set(true);
- }
- });
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ err.set((Throwable) e.getSource());
+ stopFlag.set(true);
+ }
+ });
- Window w = null;
- if (gui instanceof Window) {
- w = (Window) gui;
- } else if (gui instanceof JComponent) {
- JFrame f = new JFrame(title);
- f.setContentPane((JComponent) gui);
- f.pack();
- w = f;
- }
+ Window w = null;
+ if (gui instanceof Window) {
+ w = (Window) gui;
+ } else if (gui instanceof JComponent) {
+ JFrame f = new JFrame(title);
+ f.setContentPane((JComponent) gui);
+ f.pack();
+ w = f;
+ }
- // If it is a modal dialog, unmodalize it
- w.setModalExclusionType(ModalExclusionType.NO_EXCLUDE);
+ // If it is a modal dialog, unmodalize it
+ w.setModalExclusionType(ModalExclusionType.NO_EXCLUDE);
- if (w instanceof JDialog) {
- // JDialog.setModal must be unset additionally.
- JDialog d = (JDialog) w;
- d.setModal(false);
- }
+ if (w instanceof JDialog) {
+ // JDialog.setModal must be unset additionally.
+ JDialog d = (JDialog) w;
+ d.setModal(false);
+ }
- w.setVisible(true);
- int countWait = 0;
- while (w.isVisible() && !stopFlag.get()) {
- LangUtil.sleepExceptionless(100);
- if (waitMax >= 0 && countWait++ > waitMax * 10) {
- // waitMax < 0 will never brake the waiting and never increase
- // the countWait
- break;
- }
- }
- w.dispose();
+ w.setVisible(true);
+ int countWait = 0;
+ while (w.isVisible() && !stopFlag.get()) {
+ LangUtil.sleepExceptionless(100);
+ if (waitMax >= 0 && countWait++ > waitMax * 10) {
+ // waitMax < 0 will never brake the waiting and never increase
+ // the countWait
+ break;
+ }
+ }
+ w.dispose();
- if (stopFlag.get()) {
- throw err.get();
- }
+ if (stopFlag.get()) {
+ throw err.get();
+ }
- }
+ }
- public static void testGui(Component gui, int waitMax) throws Throwable {
- testGui(gui, gui.getClass().getSimpleName(), waitMax);
- }
+ public static void testGui(Component gui, int waitMax) throws Throwable {
+ testGui(gui, gui.getClass().getSimpleName(), waitMax);
+ }
- public static void testGui(Image image, int waitMax) throws Throwable {
+ public static void testGui(Image image, int waitMax) throws Throwable {
- if (GraphicsEnvironment.isHeadless())
- return;
+ if (GraphicsEnvironment.isHeadless())
+ return;
- JLabel imgLabel = new JLabel(new ImageIcon(image));
- testGui(imgLabel, imgLabel.getClass().getSimpleName(), waitMax);
- }
+ JLabel imgLabel = new JLabel(new ImageIcon(image));
+ testGui(imgLabel, imgLabel.getClass().getSimpleName(), waitMax);
+ }
- /**
- * Checks whether an image has a specific color/transparency at a special
- * pixel position.
- */
- public static boolean checkPixel(BufferedImage bi, int x, int y,
- Float... colorParts) {
+ /**
+ * Checks whether an image has a specific color/transparency at a special
+ * pixel position.
+ */
+ public static boolean checkPixel(BufferedImage bi, int x, int y,
+ Float... colorParts) {
- Color expectedColor = new Color(colorParts[0], colorParts[1],
- colorParts[2], colorParts[3]);
+ Color expectedColor = new Color(colorParts[0], colorParts[1],
+ colorParts[2], colorParts[3]);
- return checkPixel(bi, x, y, expectedColor);
+ return checkPixel(bi, x, y, expectedColor);
- }
+ }
- private static boolean checkPixel(BufferedImage bi, int x, int y,
- Color expected) {
- final int rgb = bi.getRGB(x, y);
+ private static boolean checkPixel(BufferedImage bi, int x, int y,
+ Color expected) {
+ final int rgb = bi.getRGB(x, y);
- final Color found = new Color(rgb, true);
+ final Color found = new Color(rgb, true);
- final boolean equals = expected.equals(found);
+ final boolean equals = expected.equals(found);
- if (!equals) {
- System.err.println("At pixel (" + x + "/" + y + ") expected "
- + expected + " but found " + found);
- }
+ if (!equals) {
+ System.err.println("At pixel (" + x + "/" + y + ") expected " + expected +
+ " but found " + found);
+ }
- return equals;
- }
+ return equals;
+ }
- public static boolean checkPixel(BufferedImage bi, int x, int y,
- int... colorParts) {
+ public static boolean checkPixel(BufferedImage bi, int x, int y,
+ int... colorParts) {
- Color expectedColor;
+ Color expectedColor;
- if (colorParts.length == 4) {
- expectedColor = new Color(colorParts[0], colorParts[1],
- colorParts[2], colorParts[3]);
- } else {
- expectedColor = new Color(colorParts[0], colorParts[1],
- colorParts[2]);
- }
+ if (colorParts.length == 4) {
+ expectedColor = new Color(colorParts[0], colorParts[1], colorParts[2],
+ colorParts[3]);
+ } else {
+ expectedColor = new Color(colorParts[0], colorParts[1], colorParts[2]);
+ }
- return checkPixel(bi, x, y, expectedColor);
- }
+ return checkPixel(bi, x, y, expectedColor);
+ }
- public static void testGui(JPanel jPanel, String title) throws Throwable {
- testGui(jPanel, title, 3);
- }
+ public static void testGui(JPanel jPanel, String title) throws Throwable {
+ testGui(jPanel, title, 3);
+ }
- public static void testGui(Component gui) throws Throwable {
- testGui(gui, WAIT_MAX_DEFAULT);
- }
+ public static void testGui(Component gui) throws Throwable {
+ testGui(gui, WAIT_MAX_DEFAULT);
+ }
- public static BufferedImage visualize(DefaultMapLayer dml) throws Throwable {
- DefaultMapContext mc = new DefaultMapContext(dml.getFeatureSource()
- .getSchema().getCoordinateReferenceSystem());
+ public static BufferedImage visualize(DefaultMapLayer dml) throws Throwable {
+ DefaultMapContext mc = new DefaultMapContext(
+ dml.getFeatureSource().getSchema().getCoordinateReferenceSystem());
- mc.addLayer(dml);
+ mc.addLayer(dml);
- StreamingRenderer sr = new StreamingRenderer();
- sr.setContext(mc);
+ StreamingRenderer sr = new StreamingRenderer();
+ sr.setContext(mc);
- final BufferedImage bi = new BufferedImage(100, 100,
- BufferedImage.TYPE_4BYTE_ABGR);
- Graphics2D g2d = bi.createGraphics();
- ReferencedEnvelope geoArea = new ReferencedEnvelope(dml
- .getFeatureSource().getBounds());
- sr.paint(g2d, new Rectangle(100, 100), geoArea);
- g2d.dispose();
+ final BufferedImage bi = new BufferedImage(100, 100,
+ BufferedImage.TYPE_4BYTE_ABGR);
+ Graphics2D g2d = bi.createGraphics();
+ ReferencedEnvelope geoArea = new ReferencedEnvelope(dml.getFeatureSource()
+ .getBounds());
+ sr.paint(g2d, new Rectangle(100, 100), geoArea);
+ g2d.dispose();
- TestingUtil.testGui(bi, 1);
+ TestingUtil.testGui(bi, 1);
- return bi;
- }
+ return bi;
+ }
- /**
- * Takes a URL to a shapefile, that may be inside a jar. The retuned UTL
- * points to a version of the shapefile copied to the tmp dir.
- *
- * @throws IOException
- * @throws URISyntaxException
- */
- public static URL copyShapefileToTemp(URL urlToShape) throws IOException,
- URISyntaxException {
- File tempDir = new File(IOUtil.getTempDir(), "shape"
- + (System.currentTimeMillis()));
- tempDir.mkdir();
+ /**
+ * Takes a URL to a shapefile, that may be inside a jar. The retuned UTL
+ * points to a version of the shapefile copied to the tmp dir.
+ * @throws IOException
+ * @throws URISyntaxException
+ */
+ public static URL copyShapefileToTemp(URL urlToShape) throws IOException,
+ URISyntaxException {
+ File tempDir = new File(IOUtil.getTempDir(), "shape" +
+ (System.currentTimeMillis()));
+ tempDir.mkdir();
- /**
- * SHP file!
- */
- final URL shpURL = IOUtil.changeUrlExt(urlToShape, "shp");
- String fileName = shpURL.getPath();
- if (shpURL.getPath().lastIndexOf("/") > 0)
- fileName = shpURL.getPath().substring(
- shpURL.getPath().lastIndexOf("/"));
+ /**
+ * SHP file!
+ */
+ final URL shpURL = IOUtil.changeUrlExt(urlToShape, "shp");
+ String fileName = shpURL.getPath();
+ if (shpURL.getPath().lastIndexOf("/") > 0)
+ fileName = shpURL.getPath().substring(shpURL.getPath().lastIndexOf("/"));
- IOUtil.copyUrl(shpURL, tempDir, false);
+ IOUtil.copyUrl(shpURL, tempDir, false);
- final URL shxURL = IOUtil.changeUrlExt(urlToShape, "shx");
- IOUtil.copyUrl(shxURL, tempDir, false);
+ final URL shxURL = IOUtil.changeUrlExt(urlToShape, "shx");
+ IOUtil.copyUrl(shxURL, tempDir, false);
- final URL grxURL = IOUtil.changeUrlExt(urlToShape, "grx");
- IOUtil.copyURLNoException(grxURL, tempDir, false);
+ final URL grxURL = IOUtil.changeUrlExt(urlToShape, "grx");
+ IOUtil.copyURLNoException(grxURL, tempDir, false);
- final URL fixURL = IOUtil.changeUrlExt(urlToShape, "fix");
- IOUtil.copyURLNoException(fixURL, tempDir, false);
+ final URL fixURL = IOUtil.changeUrlExt(urlToShape, "fix");
+ IOUtil.copyURLNoException(fixURL, tempDir, false);
- final URL qixURL = IOUtil.changeUrlExt(urlToShape, "qix");
- IOUtil.copyURLNoException(qixURL, tempDir, false);
+ final URL qixURL = IOUtil.changeUrlExt(urlToShape, "qix");
+ IOUtil.copyURLNoException(qixURL, tempDir, false);
- final URL xmlURL = IOUtil.changeUrlExt(urlToShape, "shp.xml");
- IOUtil.copyURLNoException(xmlURL, tempDir, false);
+ final URL xmlURL = IOUtil.changeUrlExt(urlToShape, "shp.xml");
+ IOUtil.copyURLNoException(xmlURL, tempDir, false);
- final URL dbfURL = IOUtil.changeUrlExt(urlToShape, "dbf");
- IOUtil.copyUrl(dbfURL, tempDir, false);
+ final URL dbfURL = IOUtil.changeUrlExt(urlToShape, "dbf");
+ IOUtil.copyUrl(dbfURL, tempDir, false);
- /**
- * Optionally copy a .cpg file that describes the
- */
- final URL cpgURL = IOUtil.changeUrlExt(urlToShape, "cpg");
- IOUtil.copyURLNoException(cpgURL, tempDir, false);
+ /**
+ * Optionally copy a .cpg file that describes the
+ */
+ final URL cpgURL = IOUtil.changeUrlExt(urlToShape, "cpg");
+ IOUtil.copyURLNoException(cpgURL, tempDir, false);
- return DataUtilities.fileToURL(new File(tempDir, fileName));
- }
+ return DataUtilities.fileToURL(new File(tempDir, fileName));
+ }
- final static String resLocation = "/schmitzm/jfree/feature/style/testLineChartShape/testKreiseLineChart.shp";
+ final static String resLocation = "/schmitzm/jfree/feature/style/testLineChartShape/testKreiseLineChart.shp";
- /**
- * Stellt Test-Features zur Verfügung, WENN die Anwendung im maven scope
- * <code>test</code> läuft.
- */
- public static FeatureCollection<SimpleFeatureType, SimpleFeature> getTestFeatures()
- throws IOException {
- // Testdatenshape einlesen
- URL resourceUrl = FeatureChartStyle.class.getResource(resLocation);
+ /**
+ * Stellt Test-Features zur Verfügung, WENN die Anwendung im maven scope
+ * <code>test</code> läuft.
+ */
+ public static FeatureCollection<SimpleFeatureType, SimpleFeature> getTestFeatures()
+ throws IOException {
+ // Testdatenshape einlesen
+ URL resourceUrl = FeatureChartStyle.class.getResource(resLocation);
- if (resourceUrl == null)
- throw new IllegalStateException(resLocation
- + " wurde nicht gefunden!");
+ if (resourceUrl == null)
+ throw new IllegalStateException(resLocation + " wurde nicht gefunden!");
- FeatureCollection<SimpleFeatureType, SimpleFeature> testFeatures = GeoImportUtil
- .readFeaturesFromShapeURL(resourceUrl);
+ FeatureCollection<SimpleFeatureType, SimpleFeature> testFeatures = GeoImportUtil.readFeaturesFromShapeURL(resourceUrl);
- if (testFeatures == null)
- throw new IllegalStateException(
- "Testfeatures konnten nicht gelesen werden");
+ if (testFeatures == null)
+ throw new IllegalStateException(
+ "Testfeatures konnten nicht gelesen werden");
- return testFeatures;
- }
+ return testFeatures;
+ }
- public static void testGui(JFreeChart chart, String frameTitle)
- throws Throwable {
- if (INTERACTIVE) {
- ChartFrame chartFrame = new ChartFrame(frameTitle, chart);
- chartFrame.pack();
+ public static void testGui(JFreeChart chart, String frameTitle)
+ throws Throwable {
+ testGui(chart,frameTitle,WAIT_MAX_DEFAULT);
+ }
- testGui(chartFrame);
- }
- }
+ public static void testGui(JFreeChart chart, String frameTitle, int waitMax)
+ throws Throwable {
+ if (INTERACTIVE) {
+ ChartFrame chartFrame = new ChartFrame(frameTitle, chart);
+ chartFrame.pack();
- /**
- * Returns the percentage of the possible maximum head size used (0 to 100)
- */
- public static double getHeapUsedPercentageOfMax() {
+ testGui(chartFrame,waitMax);
+ }
+ }
- // Get current size of heap in bytes
- long heapSize = Runtime.getRuntime().totalMemory();
+ /**
+ * Returns the percentage of the possible maximum head size used (0 to 100)
+ */
+ public static double getHeapUsedPercentageOfMax() {
- // Get maximum size of heap in bytes. The heap cannot grow beyond this
- // size.
- // Any attempt will result in an OutOfMemoryException.
- long heapMaxSize = Runtime.getRuntime().maxMemory();
+ // Get current size of heap in bytes
+ long heapSize = Runtime.getRuntime().totalMemory();
- // Get amount of free memory within the heap in bytes. This size will
- // increase
- // after garbage collection and decrease as new objects are created.
- long heapFreeSize = Runtime.getRuntime().freeMemory();
+ // Get maximum size of heap in bytes. The heap cannot grow beyond this
+ // size.
+ // Any attempt will result in an OutOfMemoryException.
+ long heapMaxSize = Runtime.getRuntime().maxMemory();
- long used = (heapSize - heapFreeSize);
+ // Get amount of free memory within the heap in bytes. This size will
+ // increase
+ // after garbage collection and decrease as new objects are created.
+ long heapFreeSize = Runtime.getRuntime().freeMemory();
- double perc = (used * 100. / heapMaxSize);
+ long used = (heapSize - heapFreeSize);
- return perc;
- }
+ double perc = (used * 100. / heapMaxSize);
+ return perc;
+ }
+
}
More information about the Schmitzm-commits
mailing list