Reşit Dönük Reşit Dönük - 2 years ago 180
Java Question

JScrollPane show only vertical bar and three dot for horizontal

I want to add only vertical scrollbar for my panel. I can do it succesfully but in horizontal view there is no dots appearing for long texts. I want to see both vertical scrollbar and three dot for long texts that doesn't fit the screen. How can I do it? By the way If I add my panel directly to the frame dots appearing.

with scrollpane

enter image description here

when adding panel directly to the frame

enter image description here

public class ScrollPaneDemo {

public static void main(String[] args) {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

for (int i = 0; i < 25; i++) {

JScrollPane scrollPane = new JScrollPane(panel);

JFrame frame = new JFrame();
frame.setSize(300, 300);


public static JLabel createLabel() {
return new JLabel(
"Long Text, Long Text, Long Text, Long Text, Long Text, Long Text, Long Text, Long Text, Long Text");


Answer Source

This is surely a bad idea, but if that's what you want then here it is. Modify your panel to override its getPreferredSize to be its default height, but its parent's width:

JPanel panel = new JPanel() {

    public Dimension getPreferredSize() {

        int h = super.getPreferredSize().height;
        int w = getParent().getSize().width;
        return new Dimension(w, h);

The parent class is the JViewport which is the "window through which you look" at the component in the scroll pane.

Now the line


does nothing because it is guaranteed that the width of the panel is the width of the viewport, which means you have nowhere to scroll to and by default the scrollbar won't appear. The only way to see the remaining text is to resize the scroll pane through resizing of the frame.

I won't be surprised if anything breaks with this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download