在JTable 中,其中一列包含不可編輯的文本,而其他功能複選框控制布爾值,這是一種常見要求是連結複選框。這表示當選擇多行並且取消選取任何複選框時,所有其他選定的複選框也將變為取消選取。同樣,如果選取一個複選框,則所有選取的複選框都應遵循該複選框。
實作 DataModel 類別:
DefaultTableModel 類別以建立重寫的擴展自訂DataModel方法:
建立帶有按鈕的控制面板:
建立SelectionAction 類別:
以下程式碼片段示範了實作:
import java.awt.*; import java.awt.event.ActionEvent; import javax.swing.*; import javax.swing.DefaultListSelectionModel; import javax.swing.table.DefaultTableModel; public class MultipleRowSelection extends JPanel { private static final int CHECK_COL = 1; private static final Object[][] DATA = { {"One", Boolean.TRUE}, {"Two", Boolean.FALSE}, {"Three", Boolean.TRUE}, {"Four", Boolean.FALSE}, {"Five", Boolean.TRUE}, {"Six", Boolean.FALSE}, {"Seven", Boolean.TRUE}, {"Eight", Boolean.FALSE}, {"Nine", Boolean.TRUE}, {"Ten", Boolean.FALSE}}; private static final String[] COLUMNS = {"Number", "CheckBox"}; private DataModel dataModel = new DataModel(DATA, COLUMNS); private JTable table = new JTable(dataModel); private DefaultListSelectionModel selectionModel; public MultipleRowSelection() { super(new BorderLayout()); this.add(new JScrollPane(table)); this.add(new ControlPanel(), BorderLayout.SOUTH); table.setPreferredScrollableViewportSize(new Dimension(250, 175)); selectionModel = (DefaultListSelectionModel) table.getSelectionModel(); } private class DataModel extends DefaultTableModel { public DataModel(Object[][] data, Object[] columnNames) { super(data, columnNames); } @Override public Class<?> getColumnClass(int columnIndex) { if (columnIndex == CHECK_COL) { return getValueAt(0, CHECK_COL).getClass(); } return super.getColumnClass(columnIndex); } @Override public boolean isCellEditable(int row, int column) { return column == CHECK_COL; } } private class ControlPanel extends JPanel { public ControlPanel() { this.add(new JLabel("Selection:")); this.add(new JButton(new SelectionAction("Clear", false))); this.add(new JButton(new SelectionAction("Check", true))); } } private class SelectionAction extends AbstractAction { boolean value; public SelectionAction(String name, boolean value) { super(name); this.value = value; } @Override public void actionPerformed(ActionEvent e) { for (int i = 0; i < dataModel.getRowCount(); i++) { if (selectionModel.isSelectedIndex(i)) { dataModel.setValueAt(value, i, CHECK_COL); } } } } private static void createAndShowUI() { JFrame frame = new JFrame("MultipleRowSelection"); frame.add(new MultipleRowSelection()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowUI(); } }); } }
透過實作這些類別和動作偵聽器,可以在JTable中選擇多行並集體切換相應的複選框,從而增強用戶體驗並簡化資料操縱。
以上是如何在 JTable 中實現連結複選框以進行多行選擇?的詳細內容。更多資訊請關注PHP中文網其他相關文章!