简体   繁体   English

复选框无法选择 - 它们是可编辑的! Java Swing

[英]Check Boxes not able to be Selected — They are Editable! Java Swing

I have read so many questions on this website concerning this problem and I cannot find why it is still not working. 我在这个网站上已经阅读了很多关于这个问题的问题,我找不到为什么它仍然没有用。

The Problem: 问题:

I made a JTable to be displayed inside a JScrollPane . 我创建了一个JTable来显示在JScrollPane The JTable is constructed as follows: JTable的构造如下:

table = new JTable(new DataTableModel());   

As you can see, I use a custom AbstractDataModel called DataTableModel . 如您所见,我使用名为DataTableModel的自定义AbstractDataModel Now, when I display this the checkboxes appear, but they are not able to be selected . 现在,当我显示此复选框时,但是无法选择它们 They are editable as you can see below. 它们是可编辑的,如下所示。 Here is the pertinent code in the DataTableModel class: (note that my column for check boxes is the first column, at index 0, and that my data in my array at this column is "null"). 以下是DataTableModel类中的相关代码:(请注意,我的复选框列是第一列,索引为0,此列中我的数据中的数据为“null”)。 For some 对于一些

public class DataTableModel extends AbstractTableModel
{
    private String[][] data;
    private String[] header =
    { "", "KB Name", "fpGUID" };

    public DataTableModel() throws SQLException
    {
        // ========= CONNECTS TO DB AND PULLS RESULTS ==========

        // GETS RESULTS SET CALLED "rs"

        // populate data array
        int counter = 0;
        while (rs.next())
        {
            //data[counter][0] = "sfsdfsdfs ";
            data[counter][1] = (String) rs.getObject(2);
            data[counter][2] = (String) rs.getObject(4);

            counter++;
        }
        // =====================================================

    }

@Override
public String getValueAt(int rowIndex, int columnIndex)
{
    return data[rowIndex][columnIndex];
}

public boolean isCellEditable(int row, int col)
{
    return col == 0;
}

public Class getColumnClass(int column)
{
    if (column == 0)
    {
        return Boolean.class;
    } else
    {
        return String.class;
    }
}

So, it seems my getColumnClass() method is fine, so what is the problem? 所以,似乎我的getColumnClass()方法没问题,那么问题是什么呢? Could it be something with my "data" which I store the data for the table. 它可能是我的“数据”,我存储表的数据。 Here is the data array: 这是数据数组:

There are a number of things that jump out... 跳出来有很多东西......

  • (As has already begin pointed out) getValueAt appears to be declared wrong. (正如已经开始指出的那样) getValueAt似乎被宣告错误。 It should be returning Object . 应该返回Object Think about it for a second. 想想它一秒钟。 Your expectation is that the first column will be boolean , so how can you return String from this method...which leads to... 您的期望是第一列将是boolean ,那么如何从此方法返回String ...这导致...
  • Your data array is an array of String ...where, again, the expectation is that the first value should be boolean . 你的data数组是一个String数组......其中,期望第一个值应该是boolean Now you can actually keep this, but you will need to translate the value to boolean from the getValueAt method and back again for the setValueAt method...which leads to... 现在你可以实际保留它,但你需要将值从getValueAt方法转换为boolean ,然后再转换为setValueAt方法...这导致...
  • You've not implemented setValueAt , so there is no way that the changes to the cell value can be stored 您尚未实现setValueAt ,因此无法存储对单元格值的更改
  • You're also not implementing getRowCount , which is required, getColumnCount , which is required and you should implement getColumnName , since you actually have some. 你也没有实现getRowCount ,这是必需的, getColumnCount ,这是必需的,你应该实现getColumnName ,因为你实际上有一些。

在此输入图像描述

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;

public class TestTableModel02 {

    public static void main(String[] args) {
        new TestTableModel02();
    }

    public TestTableModel02() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(new JTable(new DataTableModel())));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class DataTableModel extends AbstractTableModel {

        private Object[][] data;
        private String[] header = {"", "KB Name", "fpGUID"};

        public DataTableModel() {//throws SQLException {
            // ========= CONNECTS TO DB AND PULLS RESULTS ==========

            // GETS RESULTS SET CALLED "rs"

            // populate data array
//            int counter = 0;
//            while (rs.next()) {
//                //data[counter][0] = "sfsdfsdfs ";
//                data[counter][1] = (String) rs.getObject(2);
//                data[counter][2] = (String) rs.getObject(4);
//
//                counter++;
//            }
            // =====================================================

            data = new Object[4][3];
            data[0] = new Object[]{false, "Help", "1234"};
            data[1] = new Object[]{false, "On fire", "5648"};
            data[2] = new Object[]{false, "Drowning", "9012"};
            data[3] = new Object[]{false, "Micky Mouse", "3456"};
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return data[rowIndex][columnIndex];
        }

        @Override
        public boolean isCellEditable(int row, int col) {
            return col == 0;
        }

        @Override
        public Class getColumnClass(int column) {
            if (column == 0) {
                return Boolean.class;
            } else {
                return String.class;
            }
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            if (columnIndex == 0) {
                if (aValue instanceof Boolean) {
                    data[rowIndex][columnIndex] = (Boolean)aValue;
                    fireTableCellUpdated(rowIndex, columnIndex);
                }
            }
        }

        @Override
        public int getRowCount() {
            return data.length;
        }

        @Override
        public int getColumnCount() {
            return header.length;
        }

        @Override
        public String getColumnName(int column) {
            return header[column];
        }
    }
}

Now, there are ways you can get around the whole "first column must be boolean" issue, but to be frank, it's much less code to do it this way. 现在,有一些方法可以解决整个“第一列必须是布尔”问题,但坦率地说,这样做的代码要少得多。

I would also, strongly, recommend that you take a look at SwingWorker and do all your data loading using it, otherwise you may find that your UI comes to a grinding halt while the data is begin loaded, which is generally rather unpleasant. 我强烈建议您查看SwingWorker并使用它来加载所有数据,否则您可能会发现在数据开始加载时您的UI停止运转,这通常是相当不愉快的。

Take a look at... 看一眼...

For more details 更多细节

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

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