Hi,
since I'm not to familiar with Java yet (still learning ;) ) I have a problem with showing my bar chart...
The code I use was found on another part of the forum, but only works for positive values. My bar chart should also be able to display negative values. I already looked at the code to try to figure out what to change so it should also display the negative values, but since I'm kinda newbie to this and it's not an own-written program, I seem to have trouble to understand it.
So if someone could take a look at the code and tell me what to change so it supports negative values as well, I would be very very gratefull...
Thx in advance
Here is the code:
package Densigraph;
import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.text.NumberFormat;
import javax.swing.*;
public class BarGraph extends JPanel
{
double[] data;
int maxValue;
Font font;
NumberFormat nf;
final int PAD = 40;
public BarGraph()
{
data = new double[GUI.afwijking.length];
for(int i=0;i<GUI.afwijking.length;i++){
data[i] = Math.abs(GUI.afwijking);
}
font = new Font("lucida sans demibold", Font.PLAIN, 15);
nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(1);
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
double w = getWidth();
double h = getHeight();
// ordinate
g2.draw(new Line2D.Double(PAD, PAD, PAD, h - PAD));
// ordinate labels
String[] labels = getLabels();
float labelScale = (float)(h - 2*PAD)/(labels.length - 1);
g2.setFont(font);
FontRenderContext frc = g2.getFontRenderContext();
for(int j = 0; j < labels.length; j++)
{
float width = (float)font.getStringBounds(labels[j], frc).getWidth();
float height = font.getLineMetrics(labels[j], frc).getAscent();
float x = (PAD - width)/2;
float y = (float)(PAD + j*labelScale + height/2);
g2.drawString(labels[j], x, y);
}
// abcissa
g2.draw(new Line2D.Double(PAD, h - PAD, w - PAD, h - PAD));
// plot data
double xInc = (w - 2*PAD) / data.length;
double yScale = getValueScale(h);
double x1, y1, x2, y2;
int xx1,yy1,xx2,yy2;
for(int j = 0; j < data.length; j++)
{
if(j==GUI.maxindex)
g2.setPaint(Color.yellow);
else
g2.setPaint(Color.blue);
x1 = PAD + j * xInc;
y1 = h - PAD;
x2 = x1 + xInc;
y2 = y1 - data[j] * yScale;
g2.draw(new Line2D.Double(x1, y1, x1, y2));
g2.draw(new Line2D.Double(x1, y2, x2, y2));
g2.draw(new Line2D.Double(x2, y2, x2, y1));
}
}
private double getValueScale(double h)
{
int max = getMaxValue();
return (h - 2*PAD) / max;
}
private int getMaxValue()
{
int max = Integer.MIN_VALUE;
for(int j = 0; j < data.length; j++)
if(data[j] > max)
max = (int) data[j];
return max;
}
private String[] getLabels()
{
int max = getMaxValue();
double inc = max/3d;
double next = max;
String[] s = new String[4];
for(int j = 0; j < 4; j++)
s[j] = nf.format(next - j * inc);
return s;
}
}