简体   繁体   English

JButton ActionListener和JTable

[英]JButton ActionListener and JTable

Lets say I have table with saved places. 可以说我有保存位置的桌子。 And I want to sent the actual place to the editing dialog. 我想将实际位置发送到编辑对话框。

table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {            
    @Override
    public void valueChanged(ListSelectionEvent e) {
        if (!e.getValueIsAdjusting()) {
            Place p = model.getPlaceAtRow(table.getSelectedRow());
            btnEdit.addActionListener(ev -> {
                dialog.showEdit(p);
                System.out.println(p);
            });
        }
    }
});

But the problem is that places are "not deleting" from my button and edit dialog is displaying only first selected place. 但问题在于,这些位置并未从我的按钮中“删除”,并且编辑对话框仅显示第一个选定的位置。 Here is output after clicking through three places and clicking two times btnEdit: 单击三个位置并单击两次btnEdit之后,输出如下:

cz.uhk.pro.places.model.Place@4fc09588
cz.uhk.pro.places.model.Place@7003e55b
cz.uhk.pro.places.model.Place@3ba45206
cz.uhk.pro.places.model.Place@4fc09588
cz.uhk.pro.places.model.Place@7003e55b
cz.uhk.pro.places.model.Place@3ba45206

Any tips how to get previous places off from btnEdit apreciated. 如何从btnEdit获得以前的位置的任何技巧都已升值。

I suspect there is no need for the ListSelectionListener since the button's action listener could just use the currently selected row. 我怀疑没有必要使用ListSelectionListener,因为按钮的动作侦听器可以只使用当前选择的行。

eg 例如

btnEdit.addActionListener(ev -> {
    Place p = model.getPlaceAtRow(table.getSelectedRow());
    dialog.showEdit(p);
    System.out.println(p);
});

This way you only add an action listener for the button once instead of everytime there is a selection. 这样,您只需为按钮添加一个动作监听器,而不是每次都添加一个选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM