我有三个复选框,连续三列都被选中但我想从行中选择一个。如果选择其他人则取消选择

时间:2014-02-21 12:38:43

标签: java swing

我有三个复选框,连续三列都被选中但我想从行中选择一个。如果选择其他两个则取消选择....

import java.awt.*;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class CheckABunch extends JPanel {

    private static final int CHECK_COL = 2;
    @SuppressWarnings("unused")
    private static Object[][] DATA = new Object[1][1];
    private static final String[] COLUMNS = {"Number", "Present","Absent","Chk"};
    private DataModel dataModel ;
    private JTable table;
    private DefaultListSelectionModel selectionModel;
    @SuppressWarnings("unused")
    private static Integer cntrow = 0;
    private static JCheckBox jc1,jc2,jc3;



    public CheckABunch() {
        super(new BorderLayout());

        //accessing data from database

        final String driver = "com.mysql.jdbc.Driver";
        final String connection ="jdbc:mysql://localhost/search";
        final String user = "root";
        final String password = "root";

        Connection con;
        Statement st;
        ResultSet rs;
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(connection, user, password);
            st = con.createStatement();
            rs = st.executeQuery("Select count(*) from test;");
            Object[][] DATA = new Object[1][1];
            if(rs.first()){
                DATA = new Object[rs.getInt(1)][COLUMNS.length];
                cntrow = rs.getInt(1);
            }

            rs = st.executeQuery("Select * from test;");
            int i = 0;
            while (rs.next()) {
                    DATA[i][0] = rs.getString(2);
                    DATA[i][1] = new Boolean(false);
                    DATA[i][2] = new Boolean(false);
                    DATA[i][3] = new Boolean(false);
                    ++i;
                }
            dataModel = new DataModel(DATA, COLUMNS);
            table = new JTable(dataModel);
            /*
             * for (int j = 0; j < columns.length; j++) {
                System.out.println(columns[j]); 
            }
            */
            this.add(new JScrollPane(table));
            this.add(new ControlPanel(), BorderLayout.PAGE_END);
            table.setPreferredScrollableViewportSize(new Dimension(250, 175));
            selectionModel = (DefaultListSelectionModel) table.getSelectionModel();

            if (!con.isClosed()) {
                con.close();
            }
        }catch(Exception e){
            System.out.println(e);
        }


    }

    private class DataModel extends DefaultTableModel {

        public DataModel(Object[][] data, Object[] columnNames) {
            super(data, columnNames);
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            if (columnIndex == 1 || columnIndex == 2 || columnIndex == 3) {
                return getValueAt(0, 1).getClass();
            }
            return super.getColumnClass(columnIndex);
        }
        @Override
        public boolean isCellEditable(int row, int column) {
            return true;
        }
    }

    //j panel for two buttons 
    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("CheckABunch");
        frame.add(new CheckABunch());
        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();
            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

不要使用JCheckBox而是使用JRadioButtons,这里的关键是:将所有单选按钮添加到同一个ButtonGroup对象。

即,

ButtonGroup buttonGroup = new ButtonGroup();
JPanel radioPanel = new JPanel(new GridLayout(1, 0));
for (int i = 0; i < stringArray.length; i++) {
  JRadioButton radioButton = new JRadioButton(stringArray[i]);
  radioPanel.add(radioButton);
  buttonGroup.add(radioButton);
}

另外,您的代码存在其他问题:

  • 您从未向我们展示与您的问题相关的代码 - 您在其中创建并添加复选框。是的,我们看到您声明JCheckBox变量的位置,但没有代码用JCheckBox对象初始化它们或将它放在GUI中。
  • 另一方面,您显示的很多代码与手头的问题完全无关,这会分散我们理解您问题的能力。
  • 您在上面的代码中过度使用了static访问修饰符,这可能会在以后的行中产生影响。例如,您的JCheckBox变量和DATA字段不应该是静态的。