Hi!
I have a JScrollPane that contains a JPanel with a CardLayout, which in turn contains two JPanels with some labels and stuff. I want the contents of the ScrollPane/ViewPort to never exceed the width of the viewport.

The problem I'm having is that when a label holds a lot of text, the components inside of the scroll are not completely visible, they dissapear a little on each side. Is there a way of forcing a max size for the scrollpane or something so its contens never gets larger that the scrollspanes horizontal width?

mKorbel commented: nice qurstio +11

1) I have a JScrollPane that contains a JPanel with a CardLayout,

good GUI design for various screens ratio in pixels and ready for crossplatfom +1 for question

2) I want the contents of the ScrollPane/ViewPort to never exceed the width of the viewport.

basically that's contraproductive in contex that you put content to the JScrollPane,

sure you can set FontMetrics depends of available space on the screen returns from JViewport, but required to add more logics to used LayoutManager, not easy job, but is pretty possible, this is real issue for most of crossplatform applications

3) Is there a way of forcing a max size for the scrollpane or something so its contens never gets larger that the scrollspanes horizontal width?

no don't do it, because used LayotManager couldn't works correctly, recalculating JComponents size, FontMetrics shouldn't works too, every those parameters came from used LayoutManager

maybe is time to look for todays LayoutManager as f.e. MigLayout is,

I took a shortcuts by assuming that the length of a label is never gonna get wider than the viewport, if it does, we'll burn that bridge when we come to it. I stumbled upon another weird thing while trying to layout components using GridBagLayout for one of the cards in the cardLayout. The GridBagLayouts contents where set to fill hor. and ver. and the scrollpane/viewport had no preferred size or max size set. What happened was that the card panels in the card layout started getting wider and wider. I Overrode paintComponent just to print out getBounds().width. The values where growing constantly every time paintComponent was called. Bug? Feature? Must one always set preferred size?

no idea what ZOO you coded, post SSCCE that demonstrated your issue with overlap

dirty hack 1 --> ComponentListener (nothing special) can help you for getSize from visible Rectangle (JViewport) then set this size to its viewportView

dirty hack 2 --> remove JScrollpane

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.