java - 如何在 JTable 中选择行或列?

标签 java swing jtable

默认情况下,在 JTable 中,如果选择一个单元格,则会选择该单元格的整行。我想保留这个功能。

但是,标题中的按钮(每列上方)默认情况下不执行任何操作。我希望能够单击其中一个并突出显示整个列(并且我不想通过这样做来摆脱选择整行的能力)

我该如何去做呢?

最佳答案

https://kodejava.org/how-do-i-allow-row-or-column-selection-in-jtable/找到另一个例子:

“要在 JTable 组件中允许行选择或列选择或同时选择行和列,我们可以通过调用 JTable 的 setRowSelectionAllowed() 和 JTable 的 < strong>setColumnSelectionAllowed() 方法。

这两个方法都接受一个 boolean 值,指示是否允许选择。 将它们都设置为 true 允许我们从 JTable 中选择行和列。”

package org.kodejava.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());
    // sets to false to disallow row selection in the table
    // model.
    table.setRowSelectionAllowed(false);

    // Sets to true to allow column selection in the table
    // model.
    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'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];
    }
 }
}

关于java - 如何在 JTable 中选择行或列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55603379/

相关文章:

java - 用特定的实现类重写方法?

java - 我可以在处理程序/可运行对象中执行网络操作(UI 阻塞)吗?

java - setGraphic() 在递归创建的 TreeItems 上无法正常工作

java - 使用 Java2D 和 Swing 为我的 Java vector 图形编辑器创建曲线工具

java - GridLayout 中的 JLabel

java - 单击按钮打开一个新的 JFrame

java - Java中泛型模板的问题

java - 如何检索保存为 blob 的图像

java - 如何突出显示 JTable 中的特定列标题

java - 如何设置 jtable 内 jcombobox 的默认选定值?