Java如何在JTable中允许选择行或列?
为了使行选择或列选择或行和列选择JTable组件,我们可以通过调用打开和关闭JTable的setRowSelectionAllowed()和JTable的setColumnSelectionAllowed()方法。
这两种方法都接受一个boolean值,该值指示是否允许选择。设置它们两者以true允许我们从中选择行和列JTable。
package org.nhooo.example.swing; import javax.swing.*; import javax.swing.table.AbstractTableModel; import java.awt.*; public class TableAllowColumnSelection extends JPanel { public TableAllowColumnSelection() { initializePanel(); } private void initializePanel() { this.setLayout(new BorderLayout()); this.setPreferredSize(new Dimension(500, 150)); JTable table = new JTable(new PremiereLeagueTableModel()); //设置为false以禁止在表中选择行 //模型。 table.setRowSelectionAllowed(false); //设置为true以允许在表中选择列 //模型。 table.setColumnSelectionAllowed(true); JScrollPane pane = new JScrollPane(table); this.add(pane, BorderLayout.CENTER); } public static void showFrame() { JPanel panel = new TableAllowColumnSelection(); panel.setOpaque(true); JFrame frame = new JFrame("JTable Column 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() { TableAllowColumnSelection.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]; } } }