简体   繁体   中英

Java: How to make a listener get specific data from a table in Java?

Ok so I need to make a listener that by clicking on a row it will retrieve me the data from one of the columns, the ID of the element on this row, but I have no clue on how to retrieve that. So far I made a listselectionlistener but it only gets the number of the row selected, not the data in the ID column. This is the listener method. Anyone can help me with that?

//This is the listener
    ListSelectionModel model = NPC_Table.getSelectionModel();
    model.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if(!model.isSelectionEmpty()) {
                int selectedRow = model.getMinSelectionIndex();
                
            }
        }
    });

Use the parameter to method valueChanged . It contains details of the actual event, ie the action performed by the user in order to select a row in the JTable .

int idColumn = 2; // Just a guess. I assume you know the correct column index.
ListSelectionModel model = NPC_Table.getSelectionModel();
model.addListSelectionListener(new ListSelectionListener() {
    @Override
    public void valueChanged(ListSelectionEvent e) {
        if (!e.getValueIsAdjusting()) {
            int row = e.getFirstIndex();
            Object requestedValue = NPC_Table.getValueAt(row, idColumn);
        }
    }
});

Refer to How to Write a List Selection Listener .

Also consider adopting java naming conventions . Use npcTable instead of NPC_Table . Using conventions makes it easier for others to read and understand your code. After all, you are asking for help with your code, so you should make the effort to make your code as clear as possible for others to read.

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