ProjektGraph/visualizationElements/BarChart.java
2024-07-02 21:13:30 +02:00

134 lines
2.7 KiB
Java

package visualizationElements;
import java.awt.*;
import java.util.Vector;
/**
* Represents a bar chart to visualize sort algorithms.
* @author MSchaefer
*
*/
public class BarChart extends VisualizationElement {
private static final int START_X_POS = 40;
private Vector<BarChartElement> values;
private int width;
private int height;
private int startYPos;
/**
* Creates a new BarChart.
* @param values Vector with values to show as bars in the BarChart.
* @param width Width of the BarChart.
* @param heigth Height of the BarChart.
*/
public BarChart(Vector<BarChartElement> values, int width, int heigth) {
super();
this.setValues(values);
this.setWidth(width-10);
this.setHeight(heigth);
startYPos = heigth - 10;
}
/**
* Creates a new BarChart.
* @param values Array with values to show as bars in the BarChart.
* @param width Width of the BarChart.
* @param heigth Height of the BarChart.
*/
public BarChart(BarChartElement[] values, int width, int heigth) {
super();
this.setWidth(width-10);
this.setHeight(heigth);
startYPos = heigth - 10;
Vector<BarChartElement> valueVector = new Vector<BarChartElement>();
for(BarChartElement element : values){
valueVector.add(element);
}
this.setValues(valueVector);
}
@Override
public void draw(Graphics g) {
int xpos = START_X_POS;
int section = (width-20)/values.size();
for (BarChartElement barChartElement : values) {
barChartElement.draw(g, xpos, startYPos, section/2, calculateBarHeight(barChartElement));
xpos = xpos + section;
}
// Ground
g.setColor(Color.BLACK);
g.drawLine(START_X_POS - 10, startYPos, xpos-10, startYPos);
}
/**
* Calculates the height of the bar dependent of the height and value.
* Ensures that no bar is drawn downwards if the window is resized.
* @param barChartElement The BarChartElement the height is calculated for.
* @return Returns how high the bar should be drawn.
*/
private int calculateBarHeight(BarChartElement barChartElement) {
int barHeight = ((barChartElement.getValue() * (-height))/10)+20;
if(barHeight > 0){
barHeight = 0;
}
return barHeight;
}
/**
* @param values the values to set
*/
public void setValues(Vector<BarChartElement> values) {
this.values = values;
}
/**
* @return the values
*/
public Vector<BarChartElement> getValues() {
return values;
}
/**
* @param width the width to set
*/
public void setWidth(int width) {
this.width = width;
}
/**
* @return the width
*/
public int getWidth() {
return width;
}
/**
* @param height the height to set
*/
public void setHeight(int height) {
this.height = height;
}
/**
* @return the height
*/
public int getHeight() {
return height;
}
}