Skip to content

Instantly share code, notes, and snippets.

@jimwhite
Last active December 20, 2015 04:58
Show Gist options
  • Save jimwhite/6074227 to your computer and use it in GitHub Desktop.
Save jimwhite/6074227 to your computer and use it in GitHub Desktop.
Group and total a list of values and display it in a Swing table.
import groovy.swing.SwingBuilder
import javax.swing.JTable
import javax.swing.table.AbstractTableModel
import javax.swing.table.TableModel
class MyTableModel extends AbstractTableModel {
List<List> queryResult
int getRowCount() { queryResult.size() }
int getColumnCount() { queryResult[0].size() }
Object getValueAt(int rowIndex, int columnIndex) { queryResult[rowIndex][columnIndex] }
}
TableModel sourceModel = new MyTableModel(queryResult:[
['server1', 'host1', 5],
['server1', 'host1', 5],
['server1', 'host2', 10],
['server1', 'host2', 10],
['server1', 'host3', 10],
['server1', 'host3', 10],
['server1', 'host3', 10],
['server2', 'host1', 1],
['server2', 'host2', 1],
['server2', 'host2', 1],
['server2', 'host3', 3],
['server2', 'host4', 4]
])
def swingBuilder = new SwingBuilder()
JTable sourceTable
frame1 = swingBuilder.frame(title:'table test1'){
sourceTable = table(model:sourceModel)
}
frame1.pack()
frame1.show()
sourceData = (0..<(sourceTable.model.rowCount)).collect { row ->
(0..<(sourceTable.model.columnCount)).collect { sourceTable.model.getValueAt(row, it) }
}
sourceData.groupBy{[it[0],it[1]]}.each{ a,b-> println a[0]+" "+a[1] + " = " + b*.get(2).sum() }
sourceData.groupBy{[it[0],it[1]]}.each{ a,b-> println "${a[0]} ${a[1]} = ${b*.get(2).sum()}" }
println sourceData.groupBy{it[0..1]}.collectEntries { k,v-> [k, v*.get(2).sum()] }
data = sourceData.groupBy{it.take(2)}.collect { k,v-> [server:k[0], host:k[1], total:v*.get(2).sum()] }
data = data.sort(true) { -it.total }
println data
frame2 = swingBuilder.frame(title:'table test2'){
table {
tableModel( list : data ) {
propertyColumn(header:'Server', propertyName:'server')
propertyColumn(header:'Host', propertyName:'host')
propertyColumn(header:'Total', propertyName:'total')
}
}
}
frame2.pack()
frame2.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment