2

I am having trouble trying to make a click row event on my JTable work. I have added the event to my JTable, but when I run my program and click on the row, it does not show the message.

Here is my code:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.SQLException;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

public class listContacts extends JFrame {

public listContacts(){

    setLayout(new FlowLayout());

    String[] columnNames = {"GSD Number", "Scheduled Time"};
    Object [][] dataTable = {};

    DefaultTableModel listTableModel;
    listTableModel = new DefaultTableModel(dataTable, columnNames) {

        //Prevent user from editing the cells
        public boolean isCellEditable(int rowIndex, int mCollIndex){
            return false;
        }
    };

    int cont = 1;

    while(cont < 10){
        listTableModel.addRow(new Object[] {cont, cont + cont} );
        cont++;
    }


    JTable listTable = new JTable(listTableModel);

  //This is the code that adds the event to the JTable
    listTable.addMouseListener(new MouseAdapter() {

        public void rowClicked(MouseEvent e){
            JOptionPane.showMessageDialog(null,"You've clicked on this row");
        }

    });

    listTable.setCellEditor(null);

    JScrollPane pane = new JScrollPane(listTable);
    add(pane);
}


public static void main(String[] args) {
    listContacts tester = new listContacts();
    tester.setVisible(true);
    tester.setDefaultCloseOperation(EXIT_ON_CLOSE);
    tester.setSize(800, 200);
    tester.setTitle("Just a test");
}

}

Could someone help? Thanks in advance!

2 Answers2

5

Try this...

listTable.addMouseListener(new MouseAdapter() {

    // Add this annotation to your method
    @Override
    public void rowClicked(MouseEvent e){
        JOptionPane.showMessageDialog(null,"You've clicked on this row");
    }

});

Now compile it...see how it fails...

rowClicked is not a method of any interfaces or classes that MouseAdapter inherits from, therefore, nothing can ever call it, cause nothing knows about...it's not within the contractual requirements for mouse event notification.

Take a look at How to Write a Mouse Listener and java.awt.MouseListener for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

Thanks MadProgrammer, I followed your suggestions, and changed the method's name to mouseClicked and the event worked. Here is my code:

listTable.addMouseListener(new MouseAdapter() {

        // Add this annotation to your method
        @Override
        public void mouseClicked(MouseEvent e){
            JOptionPane.showMessageDialog(null,"You've clicked on this row");
        }

    });

Thanks again for the help!