I am trying to use the following Java class to add an image to a Jtable. This worked correctly. My problem is when I try to change the image of the third column to the second column (swap) using a mouse click event. But that will not work. I am changing the place of testIcon2 , testIcon1 in the mouse click event.
First, I load the image as Object[][] data = {{testIcon, "book1"}, {testIcon1, "book2"}, {testIcon2, "book3"}, {testIcon3, "book4"}};
On mouse click: Object[][] data1 = {{testIcon, "book1"}, {testIcon2, "book2"}, {testIcon1, "book3"}, {testIcon3, "book4"}};
How to change image of second column to first column when row is clicked?
public class TableIcon1 extends JFrame { private JTable table; private int pHeight = 60; public TableIcon1() { URL url = getClass().getResource("image/Pointer.GIF"); final ImageIcon testIcon = new ImageIcon(url); URL url1 = getClass().getResource("image/1.jpg"); final ImageIcon testIcon1 = new ImageIcon(url1); URL url2 = getClass().getResource("image/2.jpg"); final ImageIcon testIcon2 = new ImageIcon(url2); URL url3 = getClass().getResource("image/3.jpg"); final ImageIcon testIcon3 = new ImageIcon(url3); String[] columnNames = {"Picture", "Description"}; Object[][] data = {{testIcon , "book1"}, {testIcon1, "book2"}, {testIcon2, "book3"},{testIcon3, "book4"}}; DefaultTableModel model = new DefaultTableModel(data, columnNames); table = new JTable(model) { public Class getColumnClass(int column) { return getValueAt(1, column).getClass(); } }; table.setRowHeight(pHeight); table.setPreferredScrollableViewportSize(table.getPreferredSize()); JScrollPane scrollPane = new JScrollPane(table); add(scrollPane, BorderLayout.CENTER); table.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent event) { String[] columnNames1 = {"Picture", "Description"}; Object[][] data1 = {{testIcon , "book1"}, {testIcon2, "book2"}, {testIcon1, "book3"},{testIcon3, "book4"}}; DefaultTableModel model1 = new DefaultTableModel(data1, columnNames1); table = new JTable(model1) { public Class getColumnClass(int column) { return getValueAt(1, column).getClass(); } }; } }); } public static void main(String[] args) { TableIcon1 frame = new TableIcon1(); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.setLocation(150, 150); frame.pack(); frame.setVisible(true); } }