如何用 Java 选择 JTable 中的第一列?
要选择 JTable 中的第一列,请使用 setColumnSelectionInterval() 方法。这里,将索引设置为一个间隔和另一个间隔的终点。
对于第一列,将范围设置为 0 和 0,因为我们只想选择索引为 0(-)的第一列。
table.setColumnSelectionInterval(0, 0);
以下是如何在 JTable 中选择第一列的示例 -
示例
package my;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.border.TitledBorder;
public class SwingDemo {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "ODI Rankings", TitledBorder.CENTER, TitledBorder.TOP));
String[][] rec = {
{ "1", "Steve", "AUS" },
{ "2", "Virat", "IND" },
{ "3", "Kane", "NZ" },
{ "4", "David", "AUS" },
{ "5", "Ben", "ENG" },
{ "6", "Eion", "ENG" },
};
String[] header = { "Rank", "Player", "Country" };
JTable table = new JTable(rec, header);
table.setShowHorizontalLines(true);
table.setGridColor(Color.orange);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(false);
table.setColumnSelectionInterval(0, 0);
panel.add(new JScrollPane(table));
frame.add(panel);
frame.setSize(550, 400);
frame.setVisible(true);
}
}输出如下。现在,第一列默认被选中 -

广告
数据结构
计算机网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
JavaScript
PHP