JTable won't scroll in JScrollPane

亡梦爱人 提交于 2019-12-11 03:56:32

问题


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();
            }
        }
    });
}

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/18069673/jtable-wont-scroll-in-jscrollpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!