You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助实现JTable中复选框的联动互斥逻辑

JTable复选框互斥逻辑实现

包含复选框的JTable界面

需要在带有复选框的JTable中实现以下互斥逻辑:

  • 场景1:勾选"cricket"或"chess"复选框时,自动取消勾选同一行的"football"复选框
  • 场景2:勾选"football"复选框时,自动取消勾选同一行的"cricket"和"chess"复选框

修改后的完整代码

import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;

public final class JCheckExample extends JPanel {
    private final String[] columnNames = {"ID", "Name", "cricket","chess", "football"};
    private final Object[][] data = {{0,"Ram", false,false,true},
                                     {1,"Robert", true,false,false},
                                     {2,"Gopal", false,true,false},
                                     {3,"Rahim", true,true,false}};
    private final TableModel model = new DefaultTableModel(data, columnNames) {
        @Override
        public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        }
    };
    private final JTable table = new JTable(model);
    private final JScrollPane scrollPane = new JScrollPane(table);  

    public JCheckExample() {
        super(new BorderLayout());
        // 添加表格模型监听器,实现复选框互斥逻辑
        model.addTableModelListener(e -> {
            int row = e.getFirstRow();
            int col = e.getColumn();
            // 仅处理三个复选框列(cricket:2, chess:3, football:4)
            if (col >= 2 && col <= 4) {
                boolean isSelected = (boolean) model.getValueAt(row, col);
                if (isSelected) {
                    if (col == 2 || col == 3) {
                        // 勾选cricket或chess时,取消同一行的football
                        model.setValueAt(false, row, 4);
                    } else if (col == 4) {
                        // 勾选football时,取消同一行的cricket和chess
                        model.setValueAt(false, row, 2);
                        model.setValueAt(false, row, 3);
                    }
                }
            }
        });
        
        add(scrollPane);     
        JToggleButton check = new JToggleButton("Game Selection");
        check.addActionListener(ae -> {
            scrollPane.setVisible(!((JToggleButton)ae.getSource()).isSelected());
            scrollPane.revalidate();
        });
        add(check, BorderLayout.NORTH);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Action Setting");
        frame.setSize(375, 300);     
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new JCheckExample());      
        frame.setVisible(true);
    }
}

关键逻辑说明

通过给DefaultTableModel添加TableModelListener,监听单元格值的变化:

  1. 仅处理三个复选框对应的列(索引2、3、4)
  2. 当某复选框被勾选时,根据列索引执行对应互斥操作:
    • 若勾选cricket或chess,将同一行的football设为未勾选
    • 若勾选football,将同一行的cricket和chess设为未勾选

内容的提问来源于stack exchange,提问作者Marvel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 05:35:20