更新时间:2023-12-03 11:04:46
从如何使用表格.
您的表格模型需要几样东西.
Your table model needs several things.
getColumnClass
方法为相应的列返回 Boolean.class
.您将需要覆盖此方法.isCellEditable
方法需要为您想要使其可编辑的表列返回 true
(以便用户可以更改列的值)boolean
列传递一个有效值,否则将为 null
Boolean.class
from the getColumnClass
method for the appropriate column. You will need to override this method.isCellEditable
will need to return true
for the table column you want to make editable (so the user can change the value of the column)boolean
column for the row, otherwise it will be null
用简单的例子更新
import java.awt.EventQueue;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
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();
model.addRow(new Object[]{0, "Brian", false});
model.addRow(new Object[]{1, "Ned", false});
model.addRow(new Object[]{2, "John", false});
model.addRow(new Object[]{3, "Drogo", false});
JTable table = new JTable(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[]{"ID", "Name", "Present"}, 0);
}
@Override
public Class<?> getColumnClass(int columnIndex) {
Class clazz = String.class;
switch (columnIndex) {
case 0:
clazz = Integer.class;
break;
case 2:
clazz = Boolean.class;
break;
}
return clazz;
}
@Override
public boolean isCellEditable(int row, int column) {
return column == 2;
}
@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);
}
}
}
}
Ps- 我强烈建议您避免使用表单编辑器,直到您更好地了解 Swing 的工作原理 - 恕我直言
Ps- I would HIGHLY recommend you avoid form editors until you have a better understanding of how Swing works - IMHO