-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray2BarGraphComponent.java
More file actions
60 lines (43 loc) · 1.21 KB
/
Array2BarGraphComponent.java
File metadata and controls
60 lines (43 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//cbasurto: hw 3 problem 2 part three to take an array of ints and create a bar graph from that information
import java.awt.*;
import javax.swing.*;
import java.util.Random;
public class Array2BarGraphComponent extends JComponent{
//fields:array of bar heights and frame dimensions
private static int [] divs;
private static int width;
private static int height;
//constructor: takes as input the array it is going to plot.
public Array2BarGraphComponent(int [] a, int w, int h)
{
divs = a;
width = w;
height = h;
}
public static int getMax() {
int max=divs[0];
int i;
for(i=1;i<divs.length;i++) {
if (max < divs[i])
max=divs[i];
}
return max;
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
int barwidth = (int) Math.round((double) width/divs.length);
double barheightUnit = (double) height/getMax();
for(int i=0;i<divs.length;i++)
{
Rectangle r = new Rectangle(i*barwidth+25,
height - (int) (barheightUnit*divs[i]-25),
barwidth,
(int) (barheightUnit*divs[i]-5));
g2.setColor(Color.RED);
g2.fill(r);
g2.setColor(Color.BLACK);
g2.draw(r);
}
}
}