Skip to content

Instantly share code, notes, and snippets.

@ahmednasserpro
Created June 1, 2019 01:40
Show Gist options
  • Save ahmednasserpro/8d5cf6d294cee094cf767da804dd3d8a to your computer and use it in GitHub Desktop.
Save ahmednasserpro/8d5cf6d294cee094cf767da804dd3d8a to your computer and use it in GitHub Desktop.
Histogram class
import java.awt.*;
import javax.swing.*;
public class Histogram extends JPanel {
// Count the occurrences of 26 letters
private int[] count;
/**
* Set the count and display histogram
* @param count
*/
public void showHistogram(int[] count) {
this.count = count;
repaint();
}
@Override
/** Paint the histogram */
protected void paintComponent(Graphics g) {
if (count == null) {
return;
}
super.paintComponent(g);
// Find the panel size and bar width and interval dynamically
int width = getWidth();
int height = getHeight();
int interval = (width - 40) / count.length;
int individualWidth = (int) (((width - 40) / 26) * 0.8);
// Find the maximum count. The maximum count has the highest bar
int maxCount = 0;
for (int i = 0; i < count.length; i++) {
if (maxCount < count[i])
maxCount = count[i];
}
// x is the start position for the first bar in the histogram
int x = 30;
// Draw a horizontal base line
g.drawLine(10, height - 45, width - 10, height - 45);
g.setColor(Color.magenta);
for (int i = 0; i < count.length; i++) {
// Find the bar height
int barHeight = (int)
(((double) count[i] / (double) maxCount) * (height - 45));
// Display a bar (i.e., rectangle)
g.fillRect(x, height - 45 - barHeight, individualWidth, barHeight);
// Display a letter under the base line
g.drawString((char)(65 + i) + "", x, height - 30);
// Move x for displaying the next character
x += interval;
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment