Praise D. answered 02/11/23
I teach teenagers to code
import java.awt.*;
import javax.swing.*;
public class Histogram extends JFrame {
private int[] data;
public Histogram(int[] data) {
this.data = data;
setTitle("Histogram");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
@Override
public void paint(Graphics g) {
super.paint(g);
int width = getWidth() / data.length - 2;
int x = 1;
for (int i = 0; i < data.length; i++) {
g.drawRect(x, getHeight() - data[i], width, data[i]);
x += width + 2;
}
}
public static void main(String[] args) {
int[] data = {25, 40, 55, 70, 85, 100};
new Histogram(data);
}
}
In the program, a JFrame is created and the data array is passed as an argument to the constructor. The paint
method is overridden to draw rectangles on the frame based on the values in the data
array. The height of each rectangle is determined by the value in the data
array, and the width is calculated based on the total number of elements in the array. The x
coordinate of each rectangle is incremented by the width plus 2 to ensure there is a space between the rectangles.
I hope this helps!