I have a JScrollPane divided in two Jpanel
s as you can see in the picture:
On the right there is a JTable
with three columns. On the left there is the corresponding histogram created with JFreeChart
API.
I have to implement a listener on the histogram to ensure that when one presses on a bar, the corresponding record in the JTable
on the left is selected.
To reach my target I implement this listener:
chartPanel.addChartMouseListener(new ChartMouseListener() {
@Override
public void chartMouseMoved(ChartMouseEvent arg0) {
}
@Override
public void chartMouseClicked(ChartMouseEvent arg0) {
try{
TableModel model = table.getModel();
CategoryItemEntity entity = (CategoryItemEntity) arg0.getEntity();
Comparable row = entity.getRowKey();
Comparable col = entity.getColumnKey();
System.out.println(String.valueOf(row));
String field = String.valueOf(col);
for(int i = 0; i<model.getRowCount(); i++) {
if(model.getValueAt(i, 0).equals(field)) {
table.changeSelection(i, 0, false, false);
}
}
}
catch (Exception e) {
System.out.println("No bars selected");
}
}
});
This listener works correctly until one orders the JTable by clicking on the header. For example, if one orders the JTable according to Number of occurrences
, when one presses a bar of the histogram, the selected row in the JTable
does not correspond to the clicked bar.
---Edit
When one presses a bar, I have to selected the correspondig record in the JTable. For example, suppose one presses "Bronx" bar:
My code works correctly until one orders the JTable by clicking on the header field (borough, type, Number of Occurrences).
You must convert the view row number to exact row number.
You can do this by:
int realRowNumber = table.convertRowIndexToModel(viewRowIndex);