How to determine which cell in JTable was selected?

I have JTablea GUI and I want to return a number based on the value of the cell that the user clicks on. This is the code:

ListSelectionModel newmodel = mytable.getSelectionModel();
newmodel.addListSelectionListener(new ListSelectionListener() {
    @Override
    public void valueChanged(ListSelectionEvent e) {
        int row = mytable.getSelectedRow();
        int column = mytable.getSelectedColumn();

        int cell = getNewNum();
        datefield.setText(String.valueOf(cell));
    }
});

I have a couple of problems with this. Firstly, this method makes my table editable. Before I used this method, I could not edit the table, but now I can delete records. I looked in the API, but I do not know why this is so. Secondly, if I click on a cell in row 3, say, and then I click on another row in cell 3, the event is not logged. How can I make an event by clicking a cell in the currently selected row?

+5
1

, :

jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
    @Override
    public void mouseClicked(java.awt.event.MouseEvent evt) {
        int row = jTable1.rowAtPoint(evt.getPoint());
        int col = jTable1.columnAtPoint(evt.getPoint());
        if (row >= 0 && col >= 0) {
            ......

        }
    }
});

:

jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
       @Override
       public void mouseClicked(java.awt.event.MouseEvent evt) {
           ...
           int row = jTable1.getSelectedRow();
           int col = jTable1.getSelectedColumn());
           if (evt.getClickCount() > 1) { // double-click etc...
              ...

:

public boolean isCellEditable(int row, int col) {
   return false;
}

JTable .

, , getValueAt(row,col) JTable- :

Object foo = jTable1.getModel().getValueAt(row, col); 
+7

All Articles