I have got the following basic setup on a Part of my GUI:
A JScrollPane On it, a JPanel with a BoxLayout (new BoxLayout(tablePanel, BoxLayout.PAGE_AXIS)) And on this Panel, a Bunch ob Panels.
I am trying to scroll to the Panel that has been highlighted... this works ALMOST. Currenly, if a Panel is only half-visible on the bottom Part, the ScrollPane scrolls to make it fully visible.. great. If it is half-visible on the TOP part, it does not... I could live with that. But if a totally invisible Panel at the very bottom is highlighted, the system does not comment, but neither does it scroll there!
if(selectedPanel!=null){
Rectangle targetRectangle = new Rectangle(selectedPanel.getX(), selectedPanel.getY(), selectedPanel.getWidth(), selectedPanel.getHeight());
Rectangle r = scrollPane.getVisibleRect();
if (!r.contains(targetRectangle)) {
tablePanel.scrollRectToVisible(targetRectangle);
}
}
I am unfortunately not 100% sure how it behaves when the second-to-last panel is selected while not visible, because I cannot make that happen without some code-gymnastics; perhaps someone can help with the information I can give at this point.
you have to compare Rectangle
from/returns JViewport
(visible rectangle from JScrollPane
), not from JScrollPane
use selectedPanel.getBounds
instead of (selectedPanel.getX(), selectedPanel.getY(), selectedPanel.getWidth(), selectedPanel.getHeight());
still isn't centerred, have to divide JVievports
and selectedPanel
with 2
the same result as to use single code line JComponentPlacedIntoJScrollPane.scrollRectToVisible(selectedPanel.getBounds())
for better help sooner post an SSCCE
/MCVE
, short, runnable, compilable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With