如何使用鼠标单击事件将Jtable图像从一列更改为另一列?

时间:2012-02-11 09:51:37

标签: java image swing jtable mouseevent

我正在尝试使用以下java类将图像添加到Jtable。它运作正常。我的问题是当我尝试使用鼠标单击事件将第三列图片更改为第二列(交换)时。但它不会起作用。我在鼠标单击事件中更改了testIcon2testIcon1的位置。

首先我加载图像Object[][] data = {{testIcon, "book1"}, {testIcon1, "book2"}, {testIcon2, "book3"}, {testIcon3, "book4"}};

点击鼠标:Object[][] data1 = {{testIcon, "book1"}, {testIcon2, "book2"}, {testIcon1, "book3"}, {testIcon3, "book4"}};

如何在单击行时将第二列图像更改为第一列?

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);
    }
}

0 个答案:

没有答案