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 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 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 valueVector = new Vector(); 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 values) { this.values = values; } /** * @return the values */ public Vector 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; } }