Disables or enables JTable
‘s cell selection can be done by calling the setCellSelectionEnabled(boolean cellSelectionEnabled)
method. This method accept a boolean
value. Calling this method also changes the state of table’s row and column selection respectively.
To completely remove the selection capability from JTable
component we can change its focusable state to false
by calling the setFocusable(boolean focusable)
method.
package org.kodejava.swing;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
public class JTableDisableSelection extends JPanel {
public JTableDisableSelection() {
initializePanel();
}
public static void showFrame() {
JPanel panel = new JTableDisableSelection();
panel.setOpaque(true);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("JTable Disable Selection");
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(JTableDisableSelection::showFrame);
}
private void initializePanel() {
setLayout(new BorderLayout());
setPreferredSize(new Dimension(500, 500));
JTable table = new JTable(new PremiereLeagueTableModel());
table.getColumnModel().getColumn(0).setMinWidth(200);
// Disable table's cell selection.
table.setCellSelectionEnabled(false);
// Settings table focus to false completely remove selection
// capability from the table component.
table.setFocusable(false);
JScrollPane pane = new JScrollPane(table);
add(pane, BorderLayout.CENTER);
}
static class PremiereLeagueTableModel extends AbstractTableModel {
// TableModel's column names
private final String[] columnNames = {
"CLUB", "MP", "W", "D", "L", "GF", "GA", "GD", "PTS"
};
// TableModel's data
private final Object[][] data = {
{"Chelsea", 8, 6, 1, 1, 16, 3, 13, 19},
{"Liverpool", 8, 5, 3, 0, 22, 6, 16, 18},
{"Manchester City", 8, 5, 2, 1, 16, 3, 13, 17},
{"Brighton", 8, 4, 3, 1, 8, 5, 3, 15},
{"Tottenham", 8, 5, 0, 3, 9, 12, -3, 15}
};
public int getRowCount() {
return data.length;
}
public int getColumnCount() {
return columnNames.length;
}
@Override
public String getColumnName(int column) {
return columnNames[column];
}
public Object getValueAt(int rowIndex, int columnIndex) {
return data[rowIndex][columnIndex];
}
}
}
Latest posts by Wayan (see all)
- How do I iterate through date range in Java? - October 5, 2023
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023