There are three selection modes available in the JTable
component. The selection mode can be a single selection, a single interval selection or a multiple interval selection. To set the selection mode we call the JTable.setSelectionMode()
method and pass one of the following value as the parameter:
ListSelectionModel.SINGLE_SELECTION
ListSelectionModel.SINGLE_INTERVAL_SELECTION
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
package org.kodejava.example.swing;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
public class TableSelectionModeDemo extends JPanel {
public TableSelectionModeDemo() {
initializePanel();
}
private void initializePanel() {
this.setLayout(new BorderLayout());
JTable table = new JTable(new PremiereLeagueTableModel());
// Settings table selection mode. We can use the following
// three constants to define the selection mode.
//
// - ListSelectionModel.SINGLE_SELECTION
// - ListSelectionModel.SINGLE_INTERVAL_SELECTION
// - ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JScrollPane pane = new JScrollPane(table);
this.add(pane, BorderLayout.CENTER);
this.setPreferredSize(new Dimension(500, 150));
}
public static void showFrame() {
JPanel panel = new TableSelectionModeDemo();
panel.setOpaque(true);
JFrame frame = new JFrame("JTable Single Selection");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TableSelectionModeDemo.showFrame();
}
});
}
class PremiereLeagueTableModel extends AbstractTableModel {
// TableModel's column names
private String[] columnNames = {
"TEAM", "P", "W", "D", "L", "GS", "GA", "GD", "PTS"
};
// TableModel's data
private Object[][] data = {
{ "Liverpool", 3, 3, 0, 0, 7, 0, 7, 9 },
{ "Tottenham", 3, 3, 0, 0, 8, 2, 6, 9 },
{ "Chelsea", 3, 3, 0, 0, 8, 3, 5, 9 },
{ "Watford", 3, 3, 0, 0, 7, 2, 5, 9 },
{ "Manchester City", 3, 2, 1, 0, 9, 2, 7, 7 }
};
public int getRowCount() {
return data.length;
}
public int getColumnCount() {
return columnNames.length;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return data[rowIndex][columnIndex];
}
}
}
Latest posts by Wayan (see all)
- How do I install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020