Reputation: 43
I am writing an application that uses a JTable and I would like to be able to select individual cells so I can interact with the selected cells. The problem is that when I select a certain number of cells, the JTable thinks I have clicked more than I actually have. For instance, I click 3 cells and the JTable automatically selects a 4th.
Here is an image of my issue. I select 3 cells in the order numbered in the image, and a 4th one is selected after selecting the 3rd.
How can I solve this issue?
Runnable example. My table application looks identical to this(obviously no menus or extra crap but this is how it is setup).
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class TestTable extends JFrame {
private JPanel contentPane;
private DefaultTableModel dbModel;
private JTable table;
private JScrollPane scrollPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
TestTable frame = new TestTable();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public TestTable() {
super("Test Table");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 500);
String[] columnNames = {"Name","Sport","Years Played"};
Object[][] data = {{"Tim","Baseball","4"},
{"Josh","Hockey","6"},
{"Jessica","Volleyball","3"}};
dbModel = new DefaultTableModel(data, columnNames);
table = new JTable(dbModel);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.getColumnModel().setColumnSelectionAllowed(true);
table.setCellSelectionEnabled(true);
scrollPane = new JScrollPane(table);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
contentPane.add(scrollPane, BorderLayout.CENTER);
setContentPane(contentPane);
}
}
Upvotes: 2
Views: 103
Reputation: 205785
To enable single cell selection, use setCellSelectionEnabled(true)
, which "treats the intersection of the row and column selection models as the selected cells." See also this related answer.
Upvotes: 4