如何使用 Java 同時選擇 JTable 中的多行?
要在 JTable 中選擇多行,請使用 setRowSelectionInterval() 方法。在這裡,將索引設定為一個端點和另一個端點的間隔。
對於範圍內的多行,請設定範圍。在這裡,我們從索引 1 到索引 2 選擇行,即兩行 −
table.setRowSelectionInterval(1, 2);
以下是一個示例,說明如何在 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(false); table.setRowSelectionAllowed(true); table.addRowSelectionInterval(1, 2); panel.add(new JScrollPane(table)); frame.add(panel); frame.setSize(550, 400); frame.setVisible(true); } }
這將產生以下輸出 −
廣告