I Have a JTable with 3 columns: ID, Name and Operation. In this last column I have a button for every line ( I will post a printscreen ). When I press the button I want to access the value in the first column. I made a listener to the table and it works when I click on the table, but if I click in the button (that is in the 3rd column) it doesn't get the value ( I assume that it is because the click is not directly in the jtable).
How can I get the value when pressing the button?
Thank you
print screen of the JTable function
The listener I made:
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
if (e.getClickCount() == 1) {
final JTable jTable= (JTable)e.getSource();
final int row = table.getSelectedRow();
final int column = table.getSelectedColumn();
final int valueInCell = (Integer)table.getValueAt(row, 0);
setSelectedID(valueInCell);
System.out.println("Selecionou: "+valueInCell);
}
}
});
Instead of adding regular JButton
s to your table you could add your own custom JButton
; which would implement ActionListener
with the desired behavior when clicked (retrieve data
), and at construction time would:
data
that you want to reference in a field.ActionListener
. Such custom JButton
would look like this:
public class DataButton<T> extends JButton implements ActionListener {
private T data;
public DataButton(T data) {
this.data = data;
addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
System.out.println("Selection: " + getData());
}
public T getData() {
return data;
}
}
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.