gpt4 book ai didi

java - 根据条件设置 JTable 单元格禁用或启用?

转载 作者:行者123 更新时间:2023-11-30 08:50:14 24 4
gpt4 key购买 nike

我有一个JTable。它有四列;最后一列是复选框列。我想根据条件启用或禁用复选框。

考虑到最后一列值(复选框值)为真,则不允许用户取消选中该复选框。如果值为 false,则允许用户选择该复选框。

有什么办法吗?我试过表 iscellEditable()setRowSelectionAllowed()。但是,这些方法并没有实现我的概念。

最佳答案

基于此example ,下面的代码根据该行的模型状态来调节 isCellEditable() 实现。一旦选中,一行就不能取消选中。您可以根据需要使用合适的 renderer 更改此类行的外观。 ,如图here .

image

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

/**
* @see https://stackoverflow.com/a/31082475/230513
* @see https://stackoverflow.com/questions/7920068
* @see https://stackoverflow.com/questions/4526779
*/
public class CheckOnce extends JPanel {

private static final int CHECK_COL = 1;
private static final Object[][] DATA = {
{"One", Boolean.FALSE}, {"Two", Boolean.FALSE},
{"Three", Boolean.FALSE}, {"Four", Boolean.FALSE},
{"Five", Boolean.FALSE}, {"Six", Boolean.FALSE},
{"Seven", Boolean.FALSE}, {"Eight", Boolean.FALSE},
{"Nine", Boolean.FALSE}, {"Ten", Boolean.FALSE}};
private static final String[] COLUMNS = {"Number", "CheckBox"};
private DataModel dataModel = new DataModel(DATA, COLUMNS);
private JTable table = new JTable(dataModel);

public CheckOnce() {
super(new BorderLayout());
this.add(new JScrollPane(table));
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setPreferredScrollableViewportSize(
new Dimension(250, 10 * table.getRowHeight()));
}

private class DataModel extends DefaultTableModel {

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

@Override
public void setValueAt(Object aValue, int row, int col) {
super.setValueAt(aValue, row, col);
}

@Override
public Class<?> getColumnClass(int col) {
if (col == CHECK_COL) {
return getValueAt(0, CHECK_COL).getClass();
}
return super.getColumnClass(col);
}

@Override
public boolean isCellEditable(int row, int col) {
Object o = getValueAt(row, col);
boolean b = o instanceof Boolean && (Boolean) o;
return col == CHECK_COL && !b;
}
}

private static void createAndShowUI() {
JFrame frame = new JFrame("CheckOne");
frame.add(new CheckOnce());
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();
}
});
}
}

关于java - 根据条件设置 JTable 单元格禁用或启用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31072755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com