java - JTable 复选框(布尔)列不可编辑
问题描述
我制作了一个 JTable 并为其实现了自定义表格模型,以呈现布尔值的复选框。我遇到的问题是复选框不可编辑。
public class JTableBooleanAsCheckbox extends JPanel {
public JTableBooleanAsCheckbox() {
initializeUI();
}
private void initializeUI() {
setLayout(new BorderLayout());
setPreferredSize(new Dimension(450, 150));
JTable table = new JTable(new BooleanTableModel());
table.setFillsViewportHeight(true);
JScrollPane pane = new JScrollPane(table);
add(pane, BorderLayout.CENTER);
}
public static void showFrame() {
JPanel panel = new JTableBooleanAsCheckbox();
panel.setOpaque(true);
JFrame frame = new JFrame("JTable Boolean as Checkbox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JTableBooleanAsCheckbox.showFrame();
}
});
}
表模型如下。
class BooleanTableModel extends AbstractTableModel {
String[] columns = {"STUDENT ID", "NAME", "SCORE", "PASSED"};
Object[][] data = {
{"S001", "ALICE", 90.00, Boolean.TRUE},
{"S002", "BOB", 45.50, Boolean.FALSE},
{"S003", "CAROL", 60.00, Boolean.FALSE},
{"S004", "MALLORY", 75.80, Boolean.TRUE}
};
public int getRowCount() {
return data.length;
}
public int getColumnCount() {
return columns.length;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return data[rowIndex][columnIndex];
}
@Override
public String getColumnName(int column) {
return columns[column];
}
//
// This method is used by the JTable to define the default
// renderer or editor for each cell. For example if you have
// a boolean data it will be rendered as a check box. A
// number value is right aligned.
//
@Override
public Class<?> getColumnClass(int columnIndex) {
return data[0][columnIndex].getClass();
}
@Override
public boolean isCellEditable(int rowIndex,int columnIndex) {
if(rowIndex == 3)
return true;
return false;
}
}
这里有什么问题?我为包含复选框的单元格设置了可编辑的单元格。仍然无法更改复选框的状态(检查取消选中)。
解决方案
您isCellEditable
的BooleanTableModel
. 而不是rowIndex == 3
您需要检查columnIndex == 3
. 它应该是:
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
if(columnIndex == 3)
return true;
return false;
}
此外,您需要覆盖它的setValueAt
方法,因为该setValueAt
方法AbstractTableModel
什么都不做:
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
data[rowIndex][columnIndex] = aValue;
}
推荐阅读
- ruby-on-rails - 如何在使用 ruby on rails 5.2 过滤模型之前跳过?
- halide - 错误:在 63 处访问输入缓冲区过滤器,超出维度 2 中的最大值 (15) 已中止(核心转储)
- c - 如何正确比较 2 双打?
- java - repaint() - 组件不会出现在简单的节目中
- python - NLTK:应该使用 sent_tokenize 下载什么
- sql - 从有序表中的时间戳中查找周期
- javascript - 为什么我的函数没有显示在 html 页面中?
- amazon-cloudformation - 如何通过 CloudFormation 配置“预令牌生成”触发器?
- javascript - javascript问题中的二次方程求解器
- google-maps - 谷歌地图定价如何运作?