在 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中文网其他相关文章!