0

I have a JTable and want to get the data from each selected column. The columns are selected by mouse clicks. So, if there are 5 columns selected, the output has to be 5 string arrays.

I'm trying to do this by MouseListener, but I can get only the clicked cells, not the entire column.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
ArmMiner
  • 215
  • 3
  • 5
  • 15
  • 1
    But if you know which cell was clicked, you know the column where it belongs, don't you? – Pablo Lozano May 02 '13 at 12:29
  • Yeah, you're right, but the problem is that I don't know how to print the entire columns, which were selected. I'm not experienced with jtables. – ArmMiner May 02 '13 at 12:31
  • Please edit your question to include an [sscce](http://sscce.org/) that shows what you've tried; two columns and one row should be enough to get started. – trashgod May 03 '13 at 11:14

1 Answers1

3

You need JTable.getSelectedColumns(), but it returns the selected column indexes, so you need to access the TableModel (package javax.swing.table)

int[] columns = jtable.getSelectedColumns();
TableModel model = jtable.getModel();
int rowcount = model.getRowCount();
String[][] output = new String[columns.length][rowcount];
for (int i = 0; i < columns.length; i++)
    for (int row = 0; row < rowcount; row++){
        int column = jtable.convertColumnIndexToModel(columns[i]);
        output[i][row] = model.getValueAt(row, column).toString();
    }
johnchen902
  • 9,531
  • 1
  • 27
  • 69
  • 1
    You forget to convert from view coordinates (`JTable`) to model coordinates (`TableModel`) – Robin May 02 '13 at 12:58
  • 1
    johnchen902: Try dragging columns to see the problem; more on @Robin's point [here](http://stackoverflow.com/a/16191431/230513). – trashgod May 02 '13 at 13:24
  • 1
    Your code will only work if you do not re-arrange the columns in your `JTable`. If you would move e.g. the first column to the end of the table your code will fail. You need to use the `JTable#convert*IndexToModel` methods. An example can be found in the class javadoc of the `JTable` class – Robin May 02 '13 at 13:24
  • Note that you make a similar mistake for the rows. You do not consider the scenario where rows are filtered out. You need to retrieve the row count from the model rather then from the table – Robin May 02 '13 at 13:33
  • @Robin Oh my goddess! What situations else am I missing? – johnchen902 May 02 '13 at 13:37
  • Nothing as far as I can see – Robin May 02 '13 at 13:41
  • Thanks for the help! One more thing, how can I restrict the mouse clicks to one for each column? – ArmMiner May 02 '13 at 13:47