Java如何设置JTable的选择模式?

JTable组件中提供三种选择模式。选择模式可以是单个选择,单个间隔选择或多个间隔选择。要设置选择模式,我们调用JTable.setSelectionMode()方法并传递以下值之一作为参数:

  • ListSelectionModel.SINGLE_SELECTION

  • ListSelectionModel.SINGLE_INTERVAL_SELECTION

  • ListSelectionModel.MULTIPLE_INTERVAL_SELECTION

package org.nhooo.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());

        //设置表选择模式。我们可以使用以下内容
        // 三个常数定义选择模式。
        //
        // -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的列名
        private String[] columnNames = {
            "TEAM", "P", "W", "D", "L", "GS", "GA", "GD", "PTS"
        };

        // TableModel的数据
        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];
        }
    }
}

JTable选择模式演示