JTable with a ScrollPane misbehaving

假装没事ソ 提交于 2019-12-24 05:04:11

问题


I have a JPanel component with a JTable inside of it. When I run the code as it's written below, the table renders and updates correctly. As soon as I try to use the scrollPane approach, the table does not render at all. Can anyone explain to me why this is?

    private static class GameHistoryPanel extends JPanel {

        private DataModel model;
        private JTable table;
        private int currentRow;
        private int currentColumn;
        private final Dimension HISTORY_PANEL_DIMENSION = new Dimension(190,460);


        public GameHistoryPanel() {
            this.setLayout(new BorderLayout());
            this.model = new DataModel();
            this.table = new JTable(model);
            this.add(table.getTableHeader(), BorderLayout.NORTH);
            this.add(table, BorderLayout.CENTER);
//            JScrollPane scrollPane = new JScrollPane();
//            scrollPane.setViewportView(table);
//            this.add(scrollPane);
            setPreferredSize(HISTORY_PANEL_DIMENSION);
            this.currentRow = 0;
            this.currentColumn = 0;
        }

        public void increment(Board board, Move move) {
            model.setValueAt(move, currentRow, currentColumn);
            if(board.currentPlayer().getAlliance() == Alliance.WHITE) {
                currentColumn++;
            } else if (board.currentPlayer().getAlliance() == Alliance.BLACK) {
                currentRow++;
                currentColumn = 0;
            }
            validate();
            repaint();
        }
    }

回答1:


It appears that you are using a JTable as view of a TableModel in which each cell exists in one of two states. Visible changes to a cell should result only from a change to the model, which may be examined in preparing the cell's renderer. In particular, invoking the methods validate() and repaint() should not be required. Their presence suggests that you are altering the view without the model's knowledge, which could explain the anomaly seen.




回答2:


Try

JScrollPane scrollPane = new JScrollPane(table);
this.add(scrollPane);



回答3:


This may be stating the obvious, but remember that you can only add a JComponent to a container once.

After

this.setLayout(new BorderLayout());
this.model = new DataModel();
this.table = new JTable(model);

either you

this.add(table, BorderLayout.CENTER);
// note that table-headers should not be added explicitly
// commented out: this.add(table.getTableHeader(), BorderLayout.NORTH);

or you

JScrollPane scrollPane = new JScrollPane(table);
this.add(scrollPane);

but trying to do both will result in problems.

I recommend using Swingx's JXTable, if at all possible. Much more flexible, and out-of-the-box column sorting and hiding/reordering.



来源:https://stackoverflow.com/questions/13861263/jtable-with-a-scrollpane-misbehaving

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