Search code examples
javaswingjtablejscrollpanedefaulttablemodel

Read content of a JScrollPane


Is there a way to read the contents of a JScrollPane?

What I have implemented is a DefaultTableModel which has three columns that were added using the addColumn() method. I use this DefaultTableModel as an argument to the declaration and implementation of a JTable. This JTable is later used as an argument to the declaration and implementation of a JScrollPane. Throughout the execution of the code, I am adding nows to the DefaultTableModel using the addRow() method. My objective at hand is to read the contents of the rows that were added.

Does anyone have any suggestions? All would be appreciated!

JTabbedPane tabbedPane = new JTabbedPane();
DefaultTableModel model = new DefaultTableModel();

model.addColumn("Column1");
model.addColumn("Column2");
model.addColumn("Column3");

JTable testResults = new JTable(model) {
    @Override
    public boolean isCellEditable(int row, int column) {
        return false;
    }
};

JScrollPane resultTab = new JScrollPane(testResults);
resultTab.setName("Tab1");
resultTab.setVisible(true);

Thread thread1 = new Thread() {
    public void run() {
        if(tabbedPane.getSelectedComponent().getName().compareTo("Tab1") == 0) {
            model.addRow(new Object[]{"content1", "content2", "content3"});
            model.addRow(new Object[]{"content4", "content5", "content6"});
            ...
            ...
            ...
            model.addRow(new Object[]{"this", "will", "continue"});
        }
        else {
            model.addRow(new Object[]{"content1", "content2", "content3"});
            model.addRow(new Object[]{"content4", "content5", "content6"});
        }
    };
thread1.start();

I want to read the data "content1", "content2", "content3", "content4", "content5", "content6", etc. The ellipses represent that there is a undefined number of rows being added throughout the source code.


Solution

  • You want to read the data from DefaultTableModel and not the JScrollPane - it's just a Swing container.

    getDataVector() will help you here. It returns vector of vectors representing data in your table model.