dmoyne wrote:
public class ScrolledPane extends JFrame {
JScrollPane mainJScrollPane;
public ScrolledPane() {
super("JScrollPane Demonstration");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
init();
setVisible(true);
}
public void init() {
...
mainJPanel.validate();
// we display inofrmation of getBounds() for each jScrollPane
System.out.println("INFO :" + jScrollPaneForJTree.getBounds());
}
...
I didn't expressly find this in the Javadocs, but I'm 99% sure that a
component that isn't visible isn't going to get laid out. Why would the
system bother?
I dumped the bounds for your components AFTER it was made visible and
got real numbers. I think the is the right way to do it. I also called
"pack()" on your JFrame, just to make sure.
Example output:
GetBoundsTest: java.awt.Rectangle[x=0,y=0,width=300,height 0]
JRootPane: java.awt.Rectangle[x=9,y=32,width=282,height=159]
JPanel: java.awt.Rectangle[x=0,y=0,width=282,height=159]
JLayeredPane: java.awt.Rectangle[x=0,y=0,width=282,height=159]
JPanel: java.awt.Rectangle[x=0,y=0,width=282,height=159]
JScrollPane: java.awt.Rectangle[x=0,y=0,width=282,height=159]
JViewport: java.awt.Rectangle[x=1,y=1,width=264,height=156]
JPanel: java.awt.Rectangle[x=0,y=0,width=264,height=1090]
JScrollPane:
java.awt.Rectangle[x=0,y=0,width=264,height=100]
JViewport:
java.awt.Rectangle[x=1,y=1,width=261,height=97]
JTree: java.awt.Rectangle[x=0,y=0,width=261,height=97]
CellRendererPane:
java.awt.Rectangle[x=0,y=0,width=0,height=0]
Etc.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JTree;
import java.awt.Dimension;
import javax.swing.SwingUtilities;
public class GetBoundsTest extends JFrame {
JScrollPane mainJScrollPane;
public GetBoundsTest() {
super("JScrollPane Demonstration");
setDefaultCloseOperation(EXIT_ON_CLOSE);
init();
pack();
setSize(300, 200);
setVisible(true);
}
public void init() {
// we set main container with GridLayout
JPanel mainJPanel = new JPanel();
GridLayout layout = new GridLayout(0, 1, 20, 10);
mainJPanel.setLayout(layout);
mainJPanel.setSize(600, 400);
// we add 10 jScrollPane containing tree
for (int i = 0; i < 10; i++) {
// we create a jScrollPane containing tree
JScrollPane jScrollPaneForJTree = new JScrollPane();
jScrollPaneForJTree.setName("jScrollPaneForJTree");
JTree jTree = new JTree();
jTree.setName("jTree");
jScrollPaneForJTree.setViewportView(jTree);
// we set height to avoid shrinking when reducing height of window
jScrollPaneForJTree.setPreferredSize(new Dimension(-1,100));
mainJPanel.add(jScrollPaneForJTree);
mainJPanel.validate();
// we display inofrmation of getBounds() for each jScrollPane
System.out.println("INFO :" + jScrollPaneForJTree.getBounds());
}
mainJScrollPane = new JScrollPane(mainJPanel);
getContentPane().add(mainJScrollPane, BorderLayout.CENTER);
// we try to scroll panel to 9th component