从jtable获取对象的正确方法

时间:2015-07-21 14:51:44

标签: java swing object jtable

大家好日子; 我有表模型扩展AbstractTableModel添加对象到jtable和它的精细和工作良好 并使用此代码从表中获取对象         ListSelectionModel rowSM1 = carTable.getSelectionModel();     rowSM1.addListSelectionListener(new ListSelectionListener(){         @覆盖         public void valueChanged(ListSelectionEvent e){             if(e.getValueIsAdjusting())                 返回;             if(carTable.getSelectedRow()< 0){                 尝试{                     抛出新的异常();                 } catch(异常e1){                     // TODO自动生成的catch块                     e1.printStackTrace();                 }             } else {                 editMI.addActionListener(new ActionListener(){                     @覆盖                     public void actionPerformed(ActionEvent e){                         System.out.print(new CarTableModel(carsList).getCar(carTable.getSelectedRow())+" \ n");                     }                 });             }         }     }); 和它的工作,并给我选定行的对象 但当选择其他行给我他的对象并根据选择重复它 如果第二次选择重复两次,如果第三次选择重复3次 像下一个: 先选择 Car {id = 1,carLicense = CarLicense {id = 1,human = Human {id = 2, 第二选择 Car {id = 3,carLicense = CarLicense {id = 3,human = Human {id = 2, Car {id = 3,carLicense = CarLicense {id = 3,human = Human {id = 2, 第三选择 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, 第四选择 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, 等等 请任何解决

1 个答案:

答案 0 :(得分:1)

每次从表中选择一行时,都会添加一个新的ActionListener。 这就是你重复输出的原因。

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

这样就足够了:

               editMI.addActionListener(new ActionListener() {

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

独立于表格的选择事件。