How to set the Image in jTable cell when click(Mouse event) the row?If I select first row the image will display in that row.Then i click the second row, the image will show in the second row?how to do this using table cell renderer or prepare renderer?
3 Answers
If you just want the image to appear in the table cell, use the default renderer for ImageIcon
and ensure that your TableModel
returns ImageIcon.class
for that column.
If you want the image to appear in response to a click, consider using a variation of TablePopupEditor
with setClickCountToStart(1)
and your image as an Icon
.
This is your 4th question on displaying an image in a JTable, so I'm guessing you already know how to do that.
So if you want to update a row when the selection changes then you will need to use a ListSelectionListener. Then when the listener fires you will need to update the TableModel to remove the icon from the previous row and update the icon in the current row.
JList: previous selected item shows you you can get the row numbers to update.
-
Post your SSCCE demonstrating the problem. – camickr Feb 11 '12 at 04:01
The best way to do this, is to make you own table cell renderer.
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if(isSelected){
return new Image(); // if selected
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); // if not selected do the normal stuff
}
Something like this.

- 415
- 3
- 14
-
-
super is to call the superclass or a method of the superclass. so you have to call the method you have overridden. – NotANormalNerd Feb 10 '12 at 10:37
-
-
you have to modify the code and not just copy it. you have say where the image is found and you need to load it. have a look at the ImageIO class of java. – NotANormalNerd Feb 10 '12 at 10:46
-
oh sorry kleopatra is right. you have to place the image on a jLabel. an return th Jlabel – NotANormalNerd Feb 10 '12 at 10:48
-
-1, there is not need to create a custom renderer. JTable supports a default renderer for displaying Icons. You just add the icon to the model and override the getColumnClass() method and the proper renderer will be used. – camickr Feb 10 '12 at 16:21