Skip to content

Instantly share code, notes, and snippets.

@jtulach
Created November 17, 2013 08:28
Show Gist options
  • Save jtulach/7510833 to your computer and use it in GitHub Desktop.
Save jtulach/7510833 to your computer and use it in GitHub Desktop.
Histogram in Java and HTML+CSS
package dew.demo.histogram;
import java.util.ArrayList;
import java.util.List;
import net.java.html.json.ComputedProperty;
import net.java.html.json.Model;
import net.java.html.json.Property;
/** Model annotation generates class Data with
* one property for list of of numbers and read-only property
* for ten of bars.
*/
@Model(className = "Histogram", properties = {
@Property(name = "numbers", type = String.class)
})
final class HistoModel {
@ComputedProperty static List<Bar> bars(String numbers) {
List<Bar> arr = new ArrayList<Bar>(10);
for (int i = 0; i < 10; i++) {
arr.add(new Bar(i, 0));
}
String[] words = numbers == null ?
new String[0] : numbers.split(" ");
for (String word : words) {
try {
double n = Double.parseDouble(word);
if (n > 99) {
n = 99;
} else if (n <= 0) {
n = 0;
}
Bar b = arr.get((int) (n / 10));
b.setValue(b.getValue() + 1);
}catch (NumberFormatException ex) {
// ignore
}
}
return arr;
}
@Model(className = "Bar", properties = {
@Property(name = "index", type = int.class),
@Property(name = "value", type = int.class)
})
static class BarModel {
//
// individual styles for each bar
//
@ComputedProperty static String left(int index) {
return (index * 50 + 20) + "px";
}
@ComputedProperty static String top(int value) {
return (199 - value * 20) + "px";
}
@ComputedProperty static String height(int value) {
return 20 * value + "px";
}
}
// initialization
static {
Histogram h = new Histogram();
h.setNumbers("15 35 55 75 95");
h.applyBindings();
}
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
#graph {
position: relative;
width: 660px;
height: 216px;
margin: 8px;
padding: 0;
}
#graph ul {
position: absolute;
top: 0;
left: 32px;
width: 600px;
height: 200px;
border-left: 1px solid black;
border-bottom: 1px solid black;
}
#graph li {
position: absolute;
list-style: none;
background: lightblue;
width: 40px;
text-align: center;
border: 1px solid black;
top: 60px;
visibility: hidden;
}
</style>
</head>
<body>
<h1>Histogram Demo</h1>
<input data-bind="value: numbers, valueUpdate: 'afterkeydown'" size="80">
<div id="graph">
<ul data-bind="foreach: bars">
<li data-bind="style: { left : left, top: top, height : height, visibility : 'visible' }">
<span style="margin:8px; background: lightblue"></span>
</li>
</ul>
</div>
</body>
</html>
@jtulach
Copy link
Author

jtulach commented Nov 17, 2013

Life version of the code is available at http://dew.apidesign.org/dew/#7510833

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment