简体   繁体   中英

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:

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.

I suspect there is no need for the ListSelectionListener since the button's action listener could just use the currently selected row.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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