我正在实现一种表。为此,我使用了AbstractTableModel,但是我不知道我的代码在做什么(这就是为什么我得到一个片段来完成他的工作,但是显然我想理解)。你可以看到代码

public class TablePanel extends JPanel
{
    private JTable table;
    public TablePanel()
    {
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        table = new JTable(new MyTableModel());
        table.setFillsViewportHeight(true);
        table.setPreferredScrollableViewportSize(new Dimension(500, 100));
        JScrollPane jps = new JScrollPane(table);
        add(jps);
        add(new JScrollPane(table));
        table.setCellSelectionEnabled(true);
    }
    private class MyTableModel extends AbstractTableModel {
        private String[] columns = {"","Monday","Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        private String[][] data = {{"8:30 - 9:30","","","","","",""},
            {"9:30 - 10:30","","","","","",""},
            {"10:30 - 11:30","","","","","",""},
            {"11:30 - 12:30","","","","","",""},
            {"12:30 - 13:30","","","","","",""},
            {"13:30 - 14:30","","","","","",""},
            {"14:30 - 15:30","","","","","",""},
            {"15:30 - 16:30","","","","","",""},
            {"16:30 - 17:30","","","","","",""}};

        public int getColumnCount() {
            return columns.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columns[col];
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }
        public Object myMethod (){
            //do something
        }
    }
}


好吧,table = new JTable(new MyTableModel());是什么意思?
我以为table是一个MyTableModel实例,但这不是事实。实际上,如果我将表传递给另一个外部类,则该类将看不到myMethod主体中定义的方法MyTableModel

最佳答案

MyTableModelTableModel,但是TableModel不一定是MyTableModel

如您所知,表的模型是MyTableModel的实例,它具有所需的myMethod(),您可以使用强制转换:

JTable table = new JTable(new MyTableModel());
MyTableModel model = (MyTableModel) table.getModel();


创建和使用对模型的引用可能会更容易:

MyTableModel model = new MyTableModel();
JTable table = new JTable(model);


不要忽略包含here所示的setValueAt()的实现。

09-29 21:46