Question

Can somebody tell me why this doesn't work? The line System.out.println(table.getSelectedRow()); is red for some reason! I want each time I click a row to show me which row is selected. Am I missing something here?

            table = new JTable(data, columnNames) {


                public Class getColumnClass(int column) {
                    for (int row = 0; row < getRowCount(); row++) {
                        Object obj = getValueAt(row, column);


                        if (obj != null) {
                            return obj.getClass();
                        }
                    }

                    return Object.class;
                }


            };


        JScrollPane scroll = new JScrollPane(table);
        getContentPane().add(scroll);


        JPanel panel = new JPanel();
        getContentPane().add(panel, BorderLayout.SOUTH);



        table.addMouseListener(new MouseListener() {

            public void mousePressed(MouseEvent e) {

                System.out.println(table.getSelectedRow());

            }

        }); 
Was it helpful?

Solution

To elaborate on what @BlackBox said, table isn't a class variable, but the mouse listener you've added is technically a new inner class. That new class doesn't have access to the table variable unless it is marked as final or unless the class that contains both table and the mouse listener has a reference to table.

OTHER TIPS

Declare the table variable as final.

For more information, see Final and inner classes on this wiki page: http://en.wikipedia.org/wiki/Final_%28Java%29#Final_variables

Essentially, marking a variable as final tells the compiler the value will never change. This indication allows the compiler to capture and store values for inner classes it otherwise wouldn't have been able to do at run time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top