简体   繁体   English

如何获取 jTable 中选中复选框的值并计算它们在 Java 中的平均值

[英]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.我正在尝试在 java 中创建一个评级原型,用户可以通过单击复选框对方面进行评级。 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.我希望用户能够 select 每行中只有一个复选框。

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. .. 可以总结为一个六列的表,第一个标记为 Aspects(待评级),然后是标记为 1-5 的列,其中包含复选框。

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.我希望用户能够 select 每行中只有一个复选框。

One approach would be to create a custom TableModel to deselect the checkbox in other columns when you make a selection in a column.一种方法是创建自定义TableModel以在您在列中进行选择时取消选择其他列中的复选框。 You can override the setValueAt(...) method.您可以覆盖setValueAt(...)方法。 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.注意:通过向TableModel添加选择/取消选择逻辑,如果用户使用鼠标或键盘更改复选框的选择,代码将起作用。 A UI should always support both mouse or keyboard. UI 应该始终支持鼠标或键盘。

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.此外,通常您会使用 JRadioButton 来指示您只能进行单个选择,但这会使过程复杂化,因为您需要为 JRadioButton 创建自定义渲染器和编辑器。 You can search the site/web for examples of how this might be done.您可以搜索站点/网络以获取有关如何执行此操作的示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Android中以编程方式制作复选框时,如何从复选框中获取选中的复选框值 - How can i get checked checkboxes values from checkbox when checkbox made programmatically in android 如何计算文档数组外的字段与 MongoDB 和 Java 中的文档数组内的字段之间的平均值? - How can I calculate the average between fields outside a document array with those inside a documents array in MongoDB and Java? 如何在jtable标题中添加复选框,以便只检查列,我可以根据用户的意愿调用打印? - how to add checkbox in jtable header,so that the checked columns only i can called for print as per the user wish? 如何在 Java 中添加 JTable 中的值? - How do I add the values in Java that are inside JTable? 如果选中了 jtable 中相应复选框的复选框,如何获取另一个单元格的值? - How do I get values of another cell if a checkbox is selected of the corresponding checkbox in jtable? 我如何计算java循环中的平均年龄? - how can i calculate the average age in a java loop? Java 如何计算数组中数字的平均值? - Java How can I calculate the average of numbers in an array? 如何从jTable中获取选定的行值并将其添加到另一个jTable中? - How can I get selected row values from a jTable and add that values to another jTable? getTag,setTag复选框问题,如何使我的活动发布复选框? 其他值发布正常 - getTag, setTag checkbox issue, how can I get my activity to post checked boxes? The other values are posting ok 单击复选框后,如何使 JTable 上的复选框不可编辑? - How can I make a checkbox on JTable not editable after a checkbox is clicked?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM