在 Java 中设置是否可以选择或取消选择表格模型中的行?
我们可以使用 setRowSelectionAllowed() 设置或取消选择表格中的行。
假设如下是我们的表格 −
DefaultTableModel tableModel = new DefaultTableModel(); JTable table = new JTable(tableModel);
如果你想允许选择行,则将方法设置为 TRUE −
table.setRowSelectionAllowed(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[] { "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"}); 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"}); table.setRowHeight(3, 30); table.setRowSelectionAllowed(false); JFrame f = new JFrame(); f.setSize(600, 400); f.add(new JScrollPane(table)); f.setVisible(true); } }
输出如下。现在你将不能选择行 −
输出
广告