I have the following little program:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class ScrollPanePlay extends JFrame
{
public static void main(String[] args)
{
ScrollPanePlay frame = new ScrollPanePlay();
frame.setVisible(true);
}
public ScrollPanePlay()
{
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(this);
panel.setLayout(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("one"));
panel.add(new JLabel("two"));
panel.add(new JLabel("three"));
panel.add(new JLabel("four"));
panel.add(new JLabel("five"));
JScrollPane scrollPane = new JScrollPane(panel);
add(panel, BorderLayout.CENTER); // <== add either panel or scrollpane
pack();
}
}
If I add panel, then the labels in the panel wrap when the window is made narrow, as expected for FlowLayout.
If I add the panel to scrollpane and add the scrollpane to the frame, then the labels don't wrap, because the scrollPane is reporting sufficient width (I guess) to hold all the labels, and allows the user to scroll to see them.
I would like the scrolling behavior, but only for vertical - I would like the user to choose the width he wants to see, and have the scrollbar appear only for scrolling vertically. How can I do that?
I tried extending JScrollPane and returning true from getScrollableTracksViewportWidth()
, but, as I expected, that doesn't do what I want because it's the frame's width I want things to track, not the viewport. I tried extending JPanel and overriding getWidth to return the width of the frame, but that still left all the labels in a horizontal row, i.e., they quit wrapping. Is there something that will do this without a custom layout manager? Seems to me all we need is programmatic control of the viewport width.