Are there any event that is fired when cell is about to be selected? There is ListSelectionListener, but it has event that is fired only after selection has happened. I need some way to cancel selection event and using ListSelectionListener it is not easy as selection has already happened and I need to have some state variable that indicates if selection is normal or is cancel of a previous selection.
Are there a way to switch off selection notifications? However this is not 100% good solution (there will be problems if some listeners saves selection state in its local storage) this is better than nothing.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.JTable;
public class JTableExample extends JFrame {
/**
*
*/
private static final long serialVersionUID = 6040280633406589974L;
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JTableExample frame = new JTableExample();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JTableExample() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
table = new JTable(new MyTableModel());
ListSelectionModel selectionModel = table.getSelectionModel();
selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
selectionModel.addListSelectionListener(new MySelectionListener());
contentPane.add(table, BorderLayout.CENTER);
}
class MyTableModel extends AbstractTableModel {
/**
*
*/
private static final long serialVersionUID = -8312320171325776638L;
public int getRowCount() {
return 10;
}
public int getColumnCount() {
return 10;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return rowIndex * columnIndex;
}
}
class MySelectionListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
int selectedRow = table.getSelectedRow();
if (selectedRow == 5) {
System.out.println("I would like this selection never happened.");
}
}
}
}