Question

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.

Was it helpful?

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.

OTHER TIPS

table.getModel().getValueAt(0, 0);

This will return "contents1" from the table model.

table.getModel().getValueAt(0, 1);

This will return contents2.

Check out TabelModel for more details.

Robin has suggested a good point. You should add rows on the EDT thread. If you have a long running process that is fetching rows, then I suggest using a SwingWorker to grab those rows and add them to your TableModel. You should use the concrete implementation (DefaultTableModel in your case) to do so.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top