我创造了一个 JTable
对于4列,最后两列是 JCheckBox
锿。我想在单击第二列上的复选框后禁用第三列中的复选框,反之亦然。
public class TableTest {
public static void main(String[] args) {
new TableTest();
}
public TableTest() {
startUI();
}
public void startUI() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException |
IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
MyTableModel model = new MyTableModel();
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/survey";
Connection conn =
DriverManager.getConnection(url,"root","");
Statement stat = conn.createStatement();
ResultSet rslt=stat.executeQuery("SELECT * FROM
questions_edit");
while(rslt.next())
{
String d = rslt.getString("question_no.");
String e = rslt.getString("question");
model.addRow(new Object[]{d,e, false, false});
}
}catch(SQLException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
JTable table = new JTable();
table.setModel(model);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MyTableModel extends DefaultTableModel {
public MyTableModel() {
super(new String[]{"Question No.", "Question", "Satisfied", "Not
Satisfied"}, 0);
}
@Override
public Class<?> getColumnClass(int columnIndex) {
Class cls = String.class;
switch (columnIndex) {
case 0:
cls = Integer.class;
break;
case 2:
cls = Boolean.class;
break;
case 3:
cls = Boolean.class;
break;
}
return cls;
}
@Override
public boolean isCellEditable(int row, int column) {
switch (column) {
case 2: return true;
case 3: return true;
}
return false;
}
@Override
public void setValueAt(Object aValue, int row, int column) {
if (aValue instanceof Boolean && column == 2) {
System.out.println(aValue);
Vector rowData = (Vector)getDataVector().get(row);
rowData.set(2, (boolean)aValue);
fireTableCellUpdated(row, column);
}
else if (aValue instanceof Boolean && column == 3) {
System.out.println(aValue);
Vector rowData = (Vector)getDataVector().get(row);
rowData.set(3, (boolean)aValue);
fireTableCellUpdated(row, column);
}
}
}
}
这是我到目前为止所做的,但是第2列和第3列都是可编辑的。请帮忙。谢谢您。
1条答案
按热度按时间6qfn3psc1#
但是第2列和第3列都是可编辑的。
好吧,这就是你的想法
isCellEditable(...)
方法状态。如果不希望第3列可编辑,则需要修改代码。可能是这样的: