对于自定义TableModel,我重写 isCellEditable ,它总是返回true。
我也覆盖 setValueAt ,但不知道如何使用该方法,因此,JTable反映了通过编辑完成的更改。
以下是PersonTableModel的修改代码: -
class PersonTableModel extends AbstractTableModel{
public int getRowCount(){
return 10 ;
}
public int getColumnCount(){
return 1 ;
}
public String getColumnName(int c){
return "Name" ;
}
public Object getValueAt(int r, int c){
return "Person " + ++r ;
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true ;
}
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
//what goes here
}
}
此致 RITS
编辑:
正如表单成员所建议的,下面是我使用PersonTableModel的代码: -
public class CustomTableModel{
@SuppressWarnings("deprecation")
public static void main(String[] args){
JFrame frame = new PersonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
frame.show();
}
}
class PersonFrame extends JFrame{
@SuppressWarnings("deprecation")
public PersonFrame(){
setTitle("PersonTable");
setSize(600, 300);
TableModel model = new PersonTableModel() ;
JTable table = new JTable(model);
getContentPane().add(new JScrollPane(table), "Center") ;
show() ;
}
}
答案 0 :(得分:1)
扩展DefaultTableModel,然后您只需要覆盖isCellEditable(...)方法。除了其他有用的方法之外,默认表模型已经实现了setValueAt()方法。
如果你真的想知道setValueAt(...)方法的内容,那么请查看DefaultTableModel的源代码,了解setValueAt()如何通过调用相应的fireXXX方法通知视图模型已更改
答案 1 :(得分:1)
我会说,你的第一个版本的PersonTableModel非常接近。我假设您想要一个表格,其中一列带有标题“名称”,然后在每一行中都有一个可编辑的名称 您的更改未显示的原因是您没有用于保存它们的基础数据结构。我建议添加一个字符串数组来保存名称。那么TableModel的代码应如下所示:
class PersonTableModel extends AbstractTableModel{
String[] data;
// I would add a constructor which fills the column initially with the
// values you want to have. Like "Person 1" "Person 2" and so on.
// You can also think about passing a size value here which determines
// the capacity of the table and therefore also the rows in the table.
// (But this would require you to change the getRowCount method).
public PersonalTableModel(){
data = new String[10]
for(int i = 0; i<10; i++){
data[i] = "Person "+i;
}
}
public int getRowCount(){
return 10 ;
}
public int getColumnCount(){
return 1 ;
}
public String getColumnName(int c){
return "Name" ;
}
// Since you dont have multiple columns you only need to pass the row here
public Object getValueAt(int r){
// Simply get the corresponding String out of the data array
return data[r];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true ;
}
// Here you also dont need to pass the column index
public void setValueAt(Object aValue, int rowIndex) {
// Save the new name into the array
data[rowIndex] = aValue.toString();
}
}
希望这有帮助。