Reşit Dönük Reşit Dönük - 7 months ago 15
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++) {
panel.add(createLabel());
}

JScrollPane scrollPane = new JScrollPane(panel);
scrollPane
.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

JFrame frame = new JFrame();
frame.getContentPane().add(scrollPane);
frame.setSize(300, 300);

frame.setVisible(true);
}

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

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() {

    @Override
    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

scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

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.

Comments