tags:

views:

382

answers:

2

Hi

I want to implement following functionality but I am confused if it's possible in Java. If yes, than how? Please help:

I want to create a JTable kind of table where 1st row of table contains column names and an icon in each column i.e. in each cell of 1st row. Clicking on that icon should lead to removal of that column from table (possible using MouseListener??).

I have found many solution where I can add button to a cell in JTable but none which describes adding both text and icon (with MouseListener) to a cell. Please see if you can help and thanks a lot for reading.

+1  A: 

You can create a custom TableCellRenderer that extends JLabel. This JLabel can be created with an icon (JLabel can display icons, to the right or left of the text). You will want the getTableCellRendererComponent to test wether the row being rendered is the first or not, and if so, set the icon, otherwise do not.

For the removal action, you can add a MouseListener on the table, and when processing the mouseClicked method, you can find the cell that was clicked in by testing the rowAtPoint and columnAtPoint by creating a Point from the mouseEvent.getX() and mouseEvent.getY(). If you determine the first row with the icon was clicked, you can remove the column from the column model.

If by 1st row, you actually mean the table header, you can create the same renderer for the JTableHeader, and set the MouseListener on that component.

akf
+1  A: 

Well, I don't understand your question.

I want to create a JTable kind of table where 1st row of table contains column names and an icon

Do you mean the Table Header, like the way sorting works by displaying the column name and the sort direction?

If so then you use a custom renderer for the table header and add a MouseListener to the header to determine which column was clicked. You should be able to customize the Default Table Header Renderer to do what you want.

Or do you mean the first row of data in the table. If so then you still need to use a custom renderer but this time you add the MouseListener to the table not the table header.

In both cases you can use the TableColumnModel.removeColumn() method to remove the column from the view of the table.

camickr