简体   繁体   中英

How can I get the values of checked checkbox inside the jTable and calculate they average in Java

I am trying to create a rating prototype in java, were a use can rate the aspect by clicking the checkbox. I am trying to capture the values for selected checkbox inside the table and calculate they average. And I want the user to be able to select only one checkbox in each row.

See the image to get a clear idea of what I mean

int rating;
int checkBox;
int average = 0;
        
for(int a=0; a<jTable1.getRowCount(); a++){
    Boolean isChecked = Boolean.valueOf(jTable1.getValueAt(a, +1).toString());
    if (isChecked) {
        rating =+1;
        //get the values of the columns you need.
    } else {
        System.out.printf("Row %s is not checked \n", a);
    }
    for(int c=1; c<jTable1.getColumnCount(); c++) {
        //if( jTable1.getValueAt(c, 1).isSelected()==true){
              //rating = 1;
        //}
    }  
}

See the image here to have a clear idea of what I am saying:

https://i.stack.imgur.com/ioBw6.jpg

.. which can be summed up as a table of six columns, the first labeled Aspects (to be rated) followed by columns labeled 1-5 containing check boxes.

user can rate the aspect by clicking the checkbox.

So I would start by creating a method to return the rating for each row. Something like:

public int getRowRating(int row)
{
    if (int c = 1; c < table.getColumnCount())
    {
        if ((Boolean)getValueAt(row, c))
            return c;
    }

    //  no selection

    return 0;
}

Then you need a loop to get the rating for each row and give a total. Something like:

for (int r = 0; r < table.getRowCount(); r++)
{
    int rowRating = getRowRating(r);

    if (rowRating == 0)
        // no rating
    else
        rating += rowRating; 
}

I want the user to be able to select only one checkbox in each row.

One approach would be to create a custom TableModel to deselect the checkbox in other columns when you make a selection in a column. You can override the setValueAt(...) method. Something like:

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

public class TableSingleSelection extends JPanel
{
    public TableSingleSelection()
    {
        String[] columnNames = {"Question", "1", "2", "3"};
        Object[][] data =
        {
            {"Question 1", Boolean.TRUE, Boolean.FALSE, Boolean.FALSE,},
            {"Question 2", Boolean.FALSE, Boolean.TRUE, Boolean.FALSE,},
            {"Question 3", Boolean.FALSE, Boolean.FALSE, Boolean.TRUE,}
        };

        DefaultTableModel model = new DefaultTableModel(data, columnNames)
        {
            //  Returning the Class of each column will allow different
            //  renderers to be used based on Class
            @Override
            public Class getColumnClass(int column)
            {
                return getValueAt(0, column).getClass();
            }

            @Override
            public void setValueAt(Object value, int row, int column)
            {
                super.setValueAt(value, row, column);

                if (column == 0) return;

                //  Reset all other columns to false

                for (int i = 1; i < getColumnCount(); i++)
                {
                    if (i != column)
                    {
                        super.setValueAt(Boolean.FALSE, row, i);
                    }
                }


            }
        };

        JTable table = new JTable( model );
        table.setPreferredScrollableViewportSize(table.getPreferredSize());

        JScrollPane scrollPane = new JScrollPane( table );
        add( scrollPane );
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("Table Model Listener");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new TableSingleSelection());
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args) throws Exception
    {
        EventQueue.invokeLater( () -> createAndShowGUI() );
    }
}

Note: by adding the select/deselect logic to the TableModel , the code will work if the user uses the mouse or keyboard to change the selection of a checkbox. A UI should always support both mouse or keyboard.

Also, typically you would use a JRadioButton to indicate you can only make a single selection, but that would complicated the process as you would need to create a custom renderer and editor for the JRadioButton. You can search the site/web for examples of how this might be done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM