Java 程序以启用 JTable 中的列选择
要启用列选择,请使用 setColumnSelectionAllowed() 方法并将其设置为 TRUE −
table.setCell setColumnSelectionAllowed(true);
以下示例演示如何在表中启用列选择 −
举例
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.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.setColumnSelectionAllowed(true); table.setRowSelectionAllowed(false); panel.add(new JScrollPane(table)); frame.add(panel); frame.setSize(550, 400); frame.setVisible(true); } }
输出如下。此处,我们选择了列。现在,我们可以选择列了,因为 setColumnSelectionAllowed() 在上文中设置为 TRUE −
注意 − 别忘记设置 table.setRowSelectionAllowed(false);
广告