从 jtable 获取对象的正确方法

right way to get object from jtable

对所有人来说都是美好的一天; 我有 table model extends AbstractTableModel add objects to jtable 它很好用 并使用此代码从 table

获取对象
        ListSelectionModel rowSM1 = carTable.getSelectionModel();
    rowSM1.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting())
                return;
            if (carTable.getSelectedRow() < 0) {
                try {
                    throw new Exception();
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            } else {
                editMI.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        System.out.print(new CarTableModel(carsList).getCar(carTable.getSelectedRow())+"\n");
                    }
                });

            }
        }

    });

及其工作并给我 selected 行的对象 但是当 select 另一行给我反对并根据 selection 重复 if second select 重复两次 if third select 重复 3 次 喜欢下一个:

第一个select

Car{id=1, carLicense=CarLicense{id=1, human=Human{id=2, 

秒select

Car{id=3, carLicense=CarLicense{id=3, human=Human{id=2,
Car{id=3, carLicense=CarLicense{id=3, human=Human{id=2,

第三select

Car{id=2, carLicense=CarLicense{id=2, human=Human{id=1,
Car{id=2, carLicense=CarLicense{id=2, human=Human{id=1,
Car{id=2, carLicense=CarLicense{id=2, human=Human{id=1,

第四个select

Car{id=1, carLicense=CarLicense{id=1, human=Human{id=2,
Car{id=1, carLicense=CarLicense{id=1, human=Human{id=2,
Car{id=1, carLicense=CarLicense{id=1, human=Human{id=2,
Car{id=1, carLicense=CarLicense{id=1, human=Human{id=2,

等等 请解决

每次 select 来自 table 的行时,您都会添加一个新的 ActionListener。 这就是您获得重复输出的原因。

我看不到你的很多代码,但我认为控制列表 selection 的所有内容都是多余的。 动作事件在 "editMI" 组件本身内触发。

所以有:

               editMI.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        System.out.print(new CarTableModel(carsList).getCar(carTable.getSelectedRow())+"\n");
                    }
                });

独立于table的select离子事件。