在 Java 中如何设置表模型中的列可以被选中或取消选择?
我们可以使用 setColumnSelectionAllowed() 来设置或取消允许选择表格中的列。
假设我们的表格如下 −
DefaultTableModel tableModel = new DefaultTableModel(); JTable table = new JTable(tableModel);
如果你想允许选择列,那么将此方法设置为 TRUE −
table.setColumnSelectionAllowed(true);
如果你想禁止选择列,那么将此方法设置为 FALSE −
table.setRowSelectionAllowed(false);
以下示例中,我们禁止了选择列 −
示例
package my; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class SwingDemo { public static void main(String[] argv) throws Exception { DefaultTableModel tableModel = new DefaultTableModel(); JTable table = new JTable(tableModel); tableModel.addColumn("Language/ Technology"); tableModel.addColumn("Text Tutorial"); tableModel.addColumn("Video Tutorial"); tableModel.addColumn("Interview QA"); tableModel.addRow(new Object[] { "ASP.NET", "Yes", "Yes", "Yes"}); tableModel.addRow(new Object[] { "F#", "Yes", "No", "Yes"}); tableModel.addRow(new Object[] { "SharePoint", "Yes", "Yes", "Yes"}); tableModel.addRow(new Object[] { "AWS", "No", "No", "Yes"}); tableModel.addRow(new Object[] { "Blockchain", "Yes", "No", "Yes"}); tableModel.addRow(new Object[] { "C#", "Yes", "Yes", "Yes"}); tableModel.addRow(new Object[] { "Java", "Yes", "No", "Yes"}); tableModel.addRow(new Object[] { "NodeJS", "No", "Yes", "Yes"}); tableModel.addRow(new Object[] { "MVC", "Yes", "No", "Yes"}); table.setRowHeight(3, 30); table.setColumnSelectionAllowed(false); JFrame f = new JFrame(); f.setSize(600, 400); f.add(new JScrollPane(table)); f.setVisible(true); } }
输出如下。现在你无法选择列 −
输出
广告