如何在 Java 中使 JTable 單選?
要在 Java 中使 JTable 單選,你需要將 selection 模式設定為 SINGLE_SELECTION。假設我們的表格如下所示 −
String[][] rec = {
{ "001", "Shirts", "40" },
{ "002", "Trousers", "250" },
{ "003", "Jeans", "25" },
{ "004", "Applicances", "90" },
{ "005", "Mobile Phones", "200" },
{ "006", "Hard Disk", "150" },
};
String[] header = { "ID", "Product", "Quantity" };
JTable table = new JTable(rec, header);使用 setSelectionMode() 方法設定 selection 模式為單選 −
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
我們來看一個例子,如何在 Java 中為我們的表格設定相同內容 −
示例
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(), "Stock", TitledBorder.CENTER, TitledBorder.TOP));
String[][] rec = {
{ "001", "Shirts", "40" },
{ "002", "Trousers", "250" },
{ "003", "Jeans", "25" },
{ "004", "Applicances", "90" },
{ "005", "Mobile Phones", "200" },
{ "006", "Hard Disk", "150" },
};
String[] header = { "ID", "Product", "Quantity" };
JTable table = new JTable(rec, header);
table.setShowHorizontalLines(true);
table.setGridColor(Color.blue);
// make table single selectable
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
panel.add(new JScrollPane(table));
frame.add(panel);
frame.setSize(550, 400);
frame.setVisible(true);
}
}輸出

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP