Michael Scott
Michael Scott

Reputation: 429

JTable won't scroll in JScrollPane

I've been having trouble trying to get the table to scroll; it just won't. I've looked at other stack answers and tried them, but they aren't working; and I'm not sure if I have something conflicting with those solutions.

tableModel = new TableModel(); //Custom Table Model
table = new JTable();
table.setBorder(null);
table.setFillsViewportHeight(true);
table.setModel(tableModel);

JScrollPane tblScrollPane = new JScrollPane(table);
tblScrollPane.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
tblScrollPane.setBounds(245, 17, 560, 425);
frmServerAdministration.getContentPane().add(tblScrollPane);

EDIT: More info

So a window opens, which is the server program. Client programs connect to the server and when they do, a method is triggered in my table model class which adds a new row into the table. (I can see the row) Then at the end of that method it calls another but nothing changes in the ScrollPane. Do I need to do some kind of repainting? -

Server.updateTableScroll();

public static void updateTableScroll() {
    System.out.println("Here"); //NOTE: I do see this printed out
    int last = table.getModel().getRowCount() - 1;
    Rectangle r = table.getCellRect(last, 0, true);
    table.scrollRectToVisible(r);        
}

EDIT 2: Thoughts

So in Eclipse I use Window Builder to make the GUI, and the following for loop will display the table with the scrollbar! But when I run the same addClient() method at another point, then the scroll bar won't appear.

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Server window = new Server();
                window.frmServerAdministration.setVisible(true);
                for(int i = 0; i < 20; i++){
                    tableModel.addClient(i, String.valueOf(i));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

Upvotes: 2

Views: 2692

Answers (2)

trashgod
trashgod

Reputation: 205875

Instead of setBounds(), override getPreferredScrollableViewportSize(), as suggested here, and pack() the enclosing top-level container. Also, the API authors "recommend that you put the component in a JPanel and set the border on the JPanel."

Addendum: As a JTable listens to its TableModel, verify that the correct event is fired from the model. If you extend AbstractTableModel, one of the fireTableXxx() methods will be appropriate.

Upvotes: 4

Michael Scott
Michael Scott

Reputation: 429

All I needed to do was call this after I added data (I'm very new to table models :P ) this.fireTableStructureChanged();

Upvotes: 1

Related Questions