File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes getBounds()/getWidth() returns 0 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "getBounds()/getWidth() returns 0" Watch "getBounds()/getWidth() returns 0" New topic

getBounds()/getWidth() returns 0

Dewang Shah

Joined: Mar 14, 2001
Posts: 10
I need to add a number of labels to a Panel. If the labels are more than can be accomodated on the Panel, then I need to display a label/button to allow the user
to scroll. I do not want to use a ScrollBar.
My call to getWidth() and getBounds() both is returning 0. Thus I have no way of
knowing when a Label is outside the visible area.
I tried setLayout(null) but then none of the labels are being displayed. And even then, the function calls still return 0
//------------- Code ------------------------------------
int iw = indexPanel.getWidth();
int newPos = 0;
for(int i=0;i<indexNames.size();i++) {<br /> //indexTabs and indexNames are vectors<br /> indexTabs.addElement(new Label((String)indexNames.elementAt(i),Label.CENTER));<br /> <br /> if((newPos + ((Label)indexTabs.elementAt(i)).getWidth()) > (iw - scrollR.getWidth() - 2)) {
lastLabel = i-1;

newPos += ((Label)indexTabs.elementAt(i)).getWidth() + 2;

[This message has been edited by Dewang Shah (edited March 20, 2001).]
Brett Spell
Ranch Hand

Joined: Feb 24, 2001
Posts: 107
Your panel and other components aren't being displayed because their widths and heights are all 0. That's the default size for components, and they're normally changed when the components are added to a container that has been assigned a layout manager. The layout manager will then use the components' preferred and / or minimum widths and heights to resize them so that they become visible, but there is no layout manager being used in your code. You must either use a layout manager (which is what I'd recommend) or "manually" resize the components yourself if you want them to appear.
Brett Spell
Author, Professional Java Programming
Ken Rubin

Joined: Jul 31, 2001
Posts: 1
I'm having the same problem, but I *am* using a layout manager...several of them, in fact.
jControlPanel = (JPanel) super.getContentPanel(); jControlPanel.setMinimumSize(new Dimension(200, 500));
jControlPanel.setPreferredSize(new Dimension(300, 500));
tf1 = new JTextField(model.getFld1Text());
tf2 = new JTextField(model.getFld2Text());
tf3 = new JTextField(model.getFld3Text());
box = Box.createVerticalBox();
JPanel tp = new JPanel();

Calling getWidth() on any of the text fields returns 0.
I agree. Here's the link:
subject: getBounds()/getWidth() returns 0
It's not a secret anymore!