JTable with autoresize, horizontal scrolling and shrinkable first column

后端 未结 2 1553
花落未央
花落未央 2021-01-03 01:42

I am having trouble creating a JTable with scrollbars. I want a JTable with 2 columns and no visible scrollbars.

If I enlarge one of the columns the scrollbars shoul

2条回答
  •  感情败类
    2021-01-03 02:29

    It's not quite enough to override the getTracks method, you have to fool super's layout into doing the right-thingy if tracking:

    JTable myTable = new JTable(10, 4) {
        private boolean inLayout;
    
        @Override
        public boolean getScrollableTracksViewportWidth() {
            return hasExcessWidth();
    
        }
    
    
        @Override
        public void doLayout() {
            if (hasExcessWidth()) {
                // fool super
                autoResizeMode = AUTO_RESIZE_SUBSEQUENT_COLUMNS;
            }
            inLayout = true;
            super.doLayout();
            inLayout = false;
            autoResizeMode = AUTO_RESIZE_OFF;
        }
    
    
        protected boolean hasExcessWidth() {
            return getPreferredSize().width < getParent().getWidth();
        }
    
        @Override
        public void columnMarginChanged(ChangeEvent e) {
            if (isEditing()) {
                // JW: darn - cleanup to terminate editing ...
                removeEditor();
            }
            TableColumn resizingColumn = getTableHeader().getResizingColumn();
            // Need to do this here, before the parent's
            // layout manager calls getPreferredSize().
            if (resizingColumn != null && autoResizeMode == AUTO_RESIZE_OFF
                    && !inLayout) {
                resizingColumn.setPreferredWidth(resizingColumn.getWidth());
            }
            resizeAndRepaint();
        }
    
    };
    

    Might not be entirely complete (probably still isn't, even after the edit to take care of columnMarginChanged, copied from JXTable (of the SwingX project) which support that behaviour by an additional layout property

    xTable.setHorizontalScrollEnabled(true);
    

提交回复
热议问题