面对程序中的跟随错误

时间:2011-05-03 13:56:10

标签: java swing

jTable1 = new javax.swing.JTable();
String columns[]={"ID","Subject","Author","Type"};
jTable1.setModel(new javax.swing.table.DefaultTableModel(this.arr,columns));

jTable1.setName("jTable1"); // NOI18N

jTable1.addAncestorListener(new javax.swing.event.AncestorListener() {
    public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
    }
    public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
        jTable1AncestorAdded(evt);
    }
    public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
    }
});

jScrollPane1.setViewportView(jTable1);

在这段代码中一切都很好,但它不是在jtable中打印任何东西。即使我已检查该数组不包含空值,它包含值。没有语法错误。任何人都可以告诉我这段代码不能在表格中显示数据的原因是什么?

2 个答案:

答案 0 :(得分:1)

不确定你得到的错误是什么。

但是通过添加这样的存根数组:

static String[][] arr = {
    { "some Id1", "some subject1", "some author1", "some type1" },
    { "some Id2", "some subject2", "some author2", "some type2" } };

您的计划如下:

import javax.swing.*;
import javax.swing.event.AncestorEvent;
import javax.swing.table.DefaultTableModel;

class Test {
    static String[][] arr = {
        { "some Id1", "some subject1", "some author1", "some type1" },
        { "some Id2", "some subject2", "some author2", "some type2" } };

    public static void main(String[] args) {
        JTable jTable1 = new javax.swing.JTable();
        String columns[]={"ID","Subject","Author","Type"};
        jTable1.setModel(new DefaultTableModel(arr,columns));
        jTable1.setName("jTable1"); // NOI18N

        jTable1.addAncestorListener(new javax.swing.event.AncestorListener() {
            public void ancestorMoved(AncestorEvent evt) {}
            public void ancestorAdded(AncestorEvent evt) {
                //jTable1AncestorAdded(evt);
            }
            public void ancestorRemoved(AncestorEvent evt) {}
        });

        JScrollPane jScrollPane1 = new JScrollPane();
        jScrollPane1.setViewportView(jTable1);

        JFrame f = new JFrame();
        f.setContentPane(jScrollPane1);
        f.pack();
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

enter image description here

答案 1 :(得分:0)

您可以使用打印出问题的表模型替换DefaultTableModel。使用装饰器模式

public class DebuggingTableModel implements TableModel {
  private final TableModel tableModel;

  public DebuggingTableModel(TableModel m) {
    tableModel = m;
  }

  @Override
  public Object getValueAt(int rowIndex, int columnIndex) {
     Object result = tableModel.getValueAt(rowIndex,columnIndex);
     System.out.println("getValueAt"+rowIndex+","+columnIndex+","+result);
     return result;
  }
  //Do something similar for all other methods in TableModel
}

现在替换

jTable1.setModel(new javax.swing.table.DefaultTableModel(this.arr,columns));

jTable1.setModel(new DebuggingTableModel(
    new javax.swing.table.DefaultTableModel(this.arr,columns)));

问题会自行打印出来。