JTextField does not shrink beyond its text length in JScrollPane

3 weeks ago 12
ARTICLE AD BOX

The HorizontalScrollBarPolicy means literally that: a policy for the scrollbar, not a resizing policy. The content is still set to its preferredSize. Not displaying a scroll bar when the size could be larger than the visible area implies that the programmer is now responsible for providing means to scroll the content.

The resizing policy can be controlled by the contained component, if it implements the Scrollable interface.

For example:

static class ScrollablePanel extends JPanel implements Scrollable { public ScrollablePanel(LayoutManager layout) { super(layout); } @Override public boolean getScrollableTracksViewportWidth() { return true; // <-- the crucial policy } // everything else implemented to match default behavior @Override public boolean getScrollableTracksViewportHeight() { return false; } @Override public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } @Override public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { return 10; } @Override public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { return orientation == SwingConstants.VERTICAL? visibleRect.height: visibleRect.width; } } private static Container createMainPanel() { JPanel panel = new ScrollablePanel(new GridBagLayout()); // replaced JPanel with ScrollablePanel GridBagConstraints constraints = new GridBagConstraints(); constraints.gridy = 0; …

By unconditionally returning true from getScrollableTracksViewportWidth(), the component requests to always have the same width as the visible rectangle and hence, no horizontal scrolling takes place.

An alternative would be

@Override public boolean getScrollableTracksViewportWidth() { return getVisibleRect().width >= getMinimumSize().width; }

This policy implies that scrolling will only take place when the visible width becomes smaller than the minimum width, in other words, when the buttons wouldn’t fit into the area (the textfield has a very small minimum width). This, of course, works best when keeping the scrollbar policy at its default HORIZONTAL_SCROLLBAR_AS_NEEDED.

Read Entire Article