行选择前的JTable组件访问

时间:2014-06-23 08:14:42

标签: java swing jtable listselectionlistener

我正在使用jtable,我需要访问一个与所选行不同的行中的组件。 我遇到的问题是,当我单击组件时,行选择更改将在组件单击事件之前发生。 这是一个解释问题的SSCE。

package test;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

public class Main extends JFrame {

public static void main(String[] args) {
    new Main();
}

public Main() {
    JButton btnTest = new JButton("test");
    btnTest.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.err.println("btnTest clicked!");
        }
    });
    JButton btnTest2 = new JButton("test2");
    btnTest2.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.err.println("btnTest2 clicked!");
        }
    });
    JTable table = new JTable(new Object[][] {
            { btnTest, "test"},
            { btnTest2, "test2"},
    }, new Object[] {"btn", "desc"});
    table.setDefaultEditor(Object.class, new Editor());
    table.setDefaultRenderer(JComponent.class, new TableCellRenderer() {            
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            return (JComponent)(value);
        }
    });
    ListSelectionModel rowSM = table.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            System.err.println("new Selection!");
        }
    });
    table.setSelectionModel(rowSM);
    add(table);
    setSize(300, 300);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    setVisible(true);
}

class Editor extends AbstractCellEditor implements TableCellEditor {
    private static final long serialVersionUID = 1L;
    private JComponent item;

    @Override
    public Object getCellEditorValue() {
        return item;
    }

    @Override
    public Component getTableCellEditorComponent(JTable table,
            Object value, boolean isSelected, int row, int column) {
        item = (JComponent)value;
        item.setBackground(table.getSelectionBackground());
        return item;
    }       
}
}

当我点击按钮时,未选择该行,这是控制台结果:

new Selection!
btnTest clicked!
new Selection!

可以点击“btnTest点击!”第一λ

由于

0 个答案:

没有答案