JTable with autoresize, horizontal scrolling and shrinkable first column

后端 未结 2 1542
花落未央
花落未央 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);
    
    0 讨论(0)
  • 2021-01-03 02:48

    With the implementation of @kleopatra, I noticed that you get a scrollbar, when you reduce the size of a column and then increase it again just slightly (which happens quite often by accident). So I've slightly changed the code slightly:

    protected boolean hasExcessWidth() {
        return getPreferredSize().width - getParent().getWidth() < 50;
    }
    

    This allows to slowly increase the size of a column without loosing the auto resize.

    Not really sure yet if the magic "50" is a good measurement, but works quite well in initial tests

    0 讨论(0)
提交回复
热议问题